Start learning free

LESSON 149 OF 188 · BACKEND: SHIPPING IT

A Real Web Server: Gunicorn in Python

Practice

So far the shop ran with app.run, or the course ran it for you. That starts Flask's development server, which warns you itself: This is a development server. Do not use it in a production deployment. It's made for one developer trying things, not for real visitors.

On a server, a WSGI server runs your app instead, and gunicorn is a common one. It imports your file and, for each request, calls your Flask object as app(environ, start_response), with the request in environ. That's WSGI: the standard way Python web servers and Python apps talk.

You start gunicorn with a command line: the program's name, then options, then the app as module:variable. For example, a blog whose Flask object is site, in the file blog.py, could start with:

gunicorn --timeout 60 blog:site

Two options matter for the shop. --bind sets the address and the port: without it, gunicorn listens on 127.0.0.1:8000, which only programs on the server itself can reach, while 0.0.0.0 means every network interface. --workers sets how many copies of the app answer requests at the same time. With the full command, the check prints:

$ gunicorn --bind 0.0.0.0:8000 --workers 2 app:app
gunicorn: a web server made for real traffic; it runs your app, so app.run is never called
--bind 0.0.0.0:8000: listens on port 8000 of every network interface, so other machines can connect
--workers 2: starts 2 copies of the app (workers), so 2 requests are answered at the same time
app:app: imports app.py and serves the variable app from it, your Flask app
For each request, gunicorn calls app(environ, start_response):
GET / -> 200 OK: The shop is open

Your task: the shop's app is already written. Build the string command, one piece per part, each piece ending with a space: gunicorn, then --bind with 0.0.0.0:8000, then --workers with 2, and the app app:app last.


Assignment
Follow the Coding Tutorial to write the gunicorn command line that runs the shop on the server.


Hint
Options come before the app. The app is the file's name without .py, a colon, and the name of the variable that holds the Flask object.


STEP 1 OF 4
    Ctrl + Enter to check

    Ship Wsgi in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free