Coding, Command Line, How-To

Flask Apps with Python 3

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:

  1. Have pip3 Installed
    You’ll require pip3 to install packages into Python 3. If you don’t have it yet, run this line:

    sudo apt-get install python3-pip
    
  2. 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
    

  3. mod_wsgi for Python 3
    If you’re running Apache 2 on your server, you should consider mod_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 install libapache2-mod-wsgi-py3 instead of libapache2-mod-wsgi.

  4. 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
    

  5. MySQLdb Not Supported in Python 3
    If you’re using MySQL for your older Flask apps, you’re most likely using MySQLdb. However, it is not supported beyond Python 2. To get around this issue, you should install PyMySQL:

    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>]'
    
  6. As always, enjoy coding! 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *