Flask Using uWSGI to run a flask application


Example

The built-in werkzeug server certainly is not suitable for running production servers. The most obvious reason is the fact that the werkzeug server is single-threaded and thus can only handle one request at a time.

Because of this we want to use the uWSGI Server to serve our application instead. In this example we will install uWSGI and run a simple test application with it.

Installing uWSGI:

pip install uwsgi

It is as simple as that. If you are unsure about the python version your pip uses make it explicit:

python3 -m pip install uwsgi  # for python3
python2 -m pip install uwsgi  # for python2

Now let's create a simple test application:

app.py

from flask import Flask
from sys import version

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello uWSGI from python version: <br>" + version

application = app

In flask the conventional name for the application is app but uWSGI looks for application by default. That's why we create an alias for our app in the last line.

Now it is time to run the app:

uwsgi --wsgi-file app.py --http :5000

You should see the message "Hello uWSGI ..." by pointing your browser to localhost:5000

In order not to type in the full command everytime we will create a uwsgi.ini file to store that configuration:

uwsgi.ini

[uwsgi]
http = :9090
wsgi-file = app.py
single-interpreter = true
enable-threads = true
master = true

The http and wsgi-file options are the same as in the manual command. But there are three more options:

  • single-interpreter: It is recommended to turn this on because it might interfere with the next option

  • enable-threads: This needs to be turned on if you are using additional threads in your application. We don't use them right now but now we don't have to worry about it.

  • master: Master mode should be enable for various reasons

Now we can run the app with this command:

uwsgi --ini uwsgi.ini