{{ cat }}'s docs

flask实战: 1.2.0 初始化flask-app_initial,nginx,uwsgi

1. initial flask app

1) activate virtual env

source /vagrant/flask_blog/bin/activate

2) create app directory

cd /vagrant/flask_blog
mkdir MyBlog

3) create basic directory

cd MyBlog
mkdir ./{static,templates}

4) create app initial file

vi __init__.py

from flask import Flask

app = Flask(__name__)

def homepage():
    return "Hi there, how ya doing?"

if __name__ == "__main__":

after run vi __init__.py, press i into insert mode. after finish input, press ESC and input :wq to save and quit

2. run test

# as we install Flask before, so you can run it directly.
# if you see the output is same with below, it means everything is good.
python __init__.py
 * Running on (Press CTRL+C to quit)

although we can run flask like this, but it only listen and can not persistence. so we need a web server to proxy requests and use uwsgi to process these requests.

3. deploy web server and configure uwsgi

1) install nginx(web server, you can choose apache also) and uwsgi

yum install nginx -y
pip install uwsgi

2) configure uwsgi

vi /vagrant/flask_blog/wsgi.py

from MyBlog import app

if __name__ == "__main__":

3) uwsgi test and make configuration file

# use command line to test first
uwsgi --socket --file /vagrant/flask_blog/wsgi.py --callable app --protocol=http

# use configuration file test second
# uwsgi configuration file
vim /vagrant/flask_blog/myblog.ini
chdir = /vagrant/flask_blog
module = wsgi:app

master = true
processes = 5
threads = 2
buffer-size = 8192

socket =
# chdir is the folder where wsgi.py located in

# module indicate first wsgi-file(wsgi)
# and then application name which assigned in "__init__.py"

# master = True is setting master mode
# processes indicate the number of processes which forked by master process
# buffer-size indicate the request block size


4) configure nginx

vi /etc/nginx/conf.d/uwsgi.conf

server {
        listen 80;
        access_log /var/log/nginx/uwsgi_access.log;
        error_log /var/log/nginx/uwsgi_error.log;
        location / {
            include        uwsgi_params;
            uwsgi_param UWSGI_PYHOME /vagrant/flask_blog;
            uwsgi_param UWSGI_CHDIR /vagrant/flask_blog;
            uwsgi_param UWSGI_SCRIPT myblog:app;
# server_name should be your server's ip or domain name
# uwsgi_pass should be same with configured in myblog.ini
# UWSGI_SCRIPT indicate uwsgi configuration filename(myblog.ini, but no extension)
# and application name(app)

5) enable and start nginx uwsgi

service nginx start
chkconfig nginx on

# you can write this command into /etc/profile to make it run when OS boot up
uwsgi /vagrant/flask_blog/myblog.ini &