How to Run Your First Flask Application

Flask is micro web development framework unlike Django flask doesn’t comes with everything with end to end solution like ORM etc. Sometimes which good because you don’t want bhramhastra to kill sparrow. Such that, not to make things unnecessarily complicated Flask helps to make backend web applications with complexity

Install Flask

pip install flask 

Write you first web application

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello! My First Flask App</p>"

if __name__ == '__main__':
    app.run()

Fun the flask app, assuming above code is saved in file named webapp.py

python webapp.py

You can flask app as python script only if you call app.run() in the script

There are couple of other ways to run the flask app as follows

flask --app webapp run 

Another way is by setting environment variable FLASK_APP

export FLASK_APP=webapp.py
FLASK_APP=webapp.py
flask run 

Setting the FLASK_ENV environment variable to ‘development’ will enable debug mode.

$ export FLASK_APP=webapp.py
$ export FLASK_ENV=development
$ flask run

You can also run flask development server in debug mode with flag –debug

$ flask --app app --debug run
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with watchdog (fsevents)
 * Debugger is active!
 * Debugger PIN: 969-296-674

Run flask on all interfaces

flask run --host=0.0.0.0

So far different ways we have seen to start the flask app must be used during development only when it comes to deploying flask app on production it is recommended to use gunicorn or uWSGI .

in fact there are many WSGI servers and HTTP server to configure flask app on production such as

  1. Gunicorn
  2. Waitress
  3. mod_wsgi
  4. uWSGI
  5. gevent
  6. eventlet
  7. ASGI

Deploying flask on these platforms as follows

Gunicorn

Gunicorn is WSGI server written in Python. Gunicorn offers simple configuration and multiple worker implementation for performance.

Installing gunicorn is simple and easy

pip install gunicorn

To start gunicorn with flask app is simple, all you need to do is tell gunicorn how to find application

# equivalent to 'from hello import app'
$ gunicorn -w 4 'webapp:app'

Starting gunicorn 20.1.0
Listening at: http://127.0.0.1:8000 (x)
Using worker: sync
Booting worker with pid: x
Booting worker with pid: x
Booting worker with pid: x
Booting worker with pid: x

Where “w” option specifies how many works, that is number of processes to run. Running multiple workers using -w would take advantage of multiple cores on CPU.

To print requests information on to console use the option –access-logfile=- while gunicorn doesn’t print requests information

gunicorn -w 4 --access-logfile=-  'webapp:app'

To bind gunicorn to specific interface use -b option. To bind on all interface use -b option 0.0.0.0

gunicorn -w 4 -b 0.0.0.0 'webapp:create_app()'

Where create_app is the function which return the application instance

By default gunicorn sync worker, to add asynchronous support start gunicorn using either using either gevent or eventlet .

To use gevent:

$ gunicorn -k gevent 'webapp:app'
Starting gunicorn 20.1.0
Listening at: http://127.0.0.1:8000 (x)
Using worker: gevent
Booting worker with pid: x

To use eventlet:

$ gunicorn -k eventlet 'webapp:app'
Starting gunicorn 20.1.0
Listening at: http://127.0.0.1:8000 (x)
Using worker: eventlet
Booting worker with pid: x

How to run gunicorn in background ? to run gunicorn in background or as daemon use –daemon option

gunicorn --bind 0.0.0.0:8001 webapp.wsgi --daemon

Or,

nohup gunicorn webapp:app &

It is not secure to run gunicorn as root and recommended way is to run gunicorn behind the reverse proxy using either Apache or Ngnix

Typical deployment configuration of Nginx with guicorn behind is as follows

  server {
    listen 80;
    server_name example.org;
    access_log  /var/log/nginx/example.log;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
  }

It is also possible to run gunicorn on Unix Socket, thus ngnix can be configured to use unix socket as follows

http {
    server {
        listen          8000;
        server_name     127.0.0.1;
        location / {
            proxy_pass http://unix:/run/gunicorn.sock;
        }
    }
}

Create the empty socket file in desired location using touch command

touch /tmp/gunicorn.socket

Troubleshooting

Gunicorn is install but on terminal you are getting gunicorn command not found. In such a case create alias to gunicorn by finding where it is installed

Check where it is installed using pip show command

pip show gunicorn

Name: gunicorn
Version: 20.1.0
Summary: WSGI HTTP Server for UNIX
Home-page: https://gunicorn.org
Author: Benoit Chesneau
Author-email: benoitc@e-engura.com
License: MIT
Location: /home/ubuntu/.local/lib/python3.10/site-packages
Requires: setuptools
Required-by: 

Add it to path by updating path in ~/.profile by adding following line at the end

export PATH=$PATH:$HOME/.local/lib/python3.10/site-packages

Note that path that in bold in the above command should be equivalent to what you see in the pip show output

If you deploy flask on ngnix and you are troubled with error something like

"http" directive is not allowed here in /etc/nginx/sites-enabled/flaskApp:1

Make sure you check the ngnix configuration where some directives are not allowed in site-avaiable directory unlike main conf for example http directive is not allowed

Default image
neotam
Naveen T aka neotam. Programming language agnostic, Software architect, Python expert, Networking & DevOps engineer & consultant with 7+ years of experience in creating serious web applications, real time event-driven non blocking applications and database driven applications ranging from small scale to enterprise grade. website
Leave a Reply