Flask Simple Manual


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

Install

1
2
3
4
5
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 ‘/’.

1
2
3
4
5
6
7
from flask import Flask

application = Flask(__name__)

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

We can test the code with the command below.

1
2
3
4
5
6
7
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.

1
2
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.

1
2
3
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
; 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.

1
uwsgi --ini wsgi_hello.ini

Nginx

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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.