I’ve dabbled with Flask apps last year, but only for awhile, and only for personal projects. I have always been resistant when it comes to using Python 3, instead of Python 2. This is because many packages were written in Python 2, and had limited support in Python 3. It seems like it’s not the case now. Just by doing a simple Google, you’ll find that most packages have been upgraded to be compatible with Python 3.
According to Flask’s website, “Flask, its dependencies, and most Flask extensions support Python 3”. They also recommend starting your subsequent projects in Python 3. This means that there are many things I have to setup and reinstall in my VPS. Use this guide to help in your migration from Python 2 to Python 3 for your Flask apps:
- Have
pip3
Installed
You’ll requirepip3
to install packages into Python 3. If you don’t have it yet, run this line:sudo apt-get install python3-pip
- Install Flask and its Dependencies Using
pip3
From Now On
This is rather self-explanatory.pip3
will ensure that Python 3 will have the packages you require to run your Flask app. E.g.sudo pip3 install flask
mod_wsgi
for Python 3
If you’re running Apache 2 on your server, you should considermod_wsgi
. If you were using the mod_wsgi for Python 2 previously, you’ll need to uninstall it first:sudo apt-get -y remove libapache2-mod-wsgi
Then install the one for use with Python 3:
sudo apt-get -y install libapache2-mod-wsgi-py3
Check out this Flask guide on deploying your app on a self-hosted server using
mod_wsgi
. Basically everything should be the same, except installlibapache2-mod-wsgi-py3
instead oflibapache2-mod-wsgi
.- SQLAlchemy for Python 3
SQLAlchemy is pretty useful for database implementation. Many Flask tutorials are also using it. If you’re using it in an old Flask app over Python 2, you’ll have to upgrade it:sudo apt-get install python3-sqlalchemy
- MySQLdb Not Supported in Python 3
If you’re usingMySQL
for your older Flask apps, you’re most likely usingMySQLdb
. However, it is not supported beyond Python 2. To get around this issue, you should installPyMySQL
:sudo pip3 install pymysql
In your SQLAlchemy database URI configuration for your Flask app, change it to ‘
mysql+pymysql://...
‘, instead of ‘mysql://...
‘ from before:app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]'
As always, enjoy coding! 🙂