Flask Simple Manual


Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

Install

virtualenv ~/.env/flask/ --python=python2.7
source ~/.env/flask/bin/activate
pip install Flask
pip install uWSGI  # Be used for production development
pacman -S nginx

Simple Example

We need a simple example to test our deployment. It returns ‘Hello World!’ when client request ‘/’.

from flask import Flask

application = Flask(__name__)

@application.route('/')
def hello():
    return "Hello World!"

We can test the code with the command below.

FLASK_APP=hello.py flask run
 * Serving Flask app "hello.py"
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

And test with curl.

curl localhost:5000
Hello World!

Production Deployment

uWSGI

Flaskā€™s built-in server is not suitable for production. We can deploy Flask in multiple ways. For more details, check here.

We will use uWSGI. You can start multiple servers with commands below. They can listen to a http port or a unix domain socket.

uwsgi --http :8080 --manage-script-name --mount /hello=hello:application
uwsgi --socket ~/Documents/flask/hello.sock --manage-script-name --mount /hello=hello:application --chmod-socket=664
uwsgi --socket ~/Documents/flask/hello.sock --manage-script-name --mount /hello=hello:application --workers 3

All the uwsgi command arguments can be set in a configuration file.

; wsgi_hello.ini
[uwsgi]
workdir = /tmp/flask

; socket and http port
socket = /tmp/flask/hello.sock
chmod-socket = 664
;http = 127.0.0.1:8080

; enable the stats server on port 9191
stats = 127.0.0.1:9191

; master and process setting
master = true
processes = 4
threads = 2

; set mountpoints
plugin = python
mount = /hello=hello:application
manage-script-name = true

;wsgi-file = hello.py
;callable = application

Spawn the server with command below.

uwsgi --ini wsgi_hello.ini

Nginx

Nginx will be the front server of uWSGI. Here’s the config file.

cat /etc/nginx/conf.d/flask.conf
upstream flask {
    server unix:///tmp/flask/hello.sock;
    #server 172.17.0.1:8080;
}

server {
    listen 8080;
    server_name flask_name;

    location /hello {
        include uwsgi_params;
        uwsgi_pass flask;
        #proxy_pass http://flask;
    }
}

systemctl restart nginx

Test with 8080/tcp.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.