down angle photography of red clouds and blue sky

How to run Python Flask Application?

I mostly use Python Flask when I need to develop a Web App or API.

Why? Because it is:

  • lightweight
  • Very Flexible
  • Micro-Service Friendly
  • Fast Development

These are one of the main reasons I choose Flask. But mostly I love to code with Flask. There are so many ways to run flask applications. I will write some of them here with code examples.

Let us assume a micro web application named mweb.py having code –

from flask import Flask

app = Flask(__name__)


@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"


if __name__ == "__main__":
    app.run(
        host="127.0.0.1",
        port=7557
    )

I can run this application with several ways.

Way 1: Run Flask application with flask command itself

$ flask run

or

$ python3 -m flask run

But both of them Will run with default flask port, which is 5000, instead of the port mentioned in the code. If we run this way, we can change the port by passing –host and –port parameter.

Way 2: Running the app.py with python3 or python itself

$ python3 app.py

This way, application will run if and only if you call the function app.run(). The host and port declared in the application will be used.

Way 3: Running flask app with Gunicorn

$ gunicorn app:app

This will run the application but default gunicorns host and port. We can change it by passing parameters.

We can also run with gunicorn using configuration file.

Gunicorn configuration can be written with a default file named gunicorn.conf.py

import multiprocessing

bind = "127.0.0.1:8778"
workers = multiprocessing.cpu_count() * 2 + 1

This configuration file is with python syntax.

$ gunicorn app:app -c gunicorn.conf.py

Way 4: Running flask app with uWSGI

$ uwsgi --http 127.0.0.1:3031 --wsgi-file app.py --callable app

We can also use a config file for uWSGI.

$ uwsgi --ini uwsgi.ini

uwsgi.ini

[uwsgi]
module = app:app

master = true
processes = 2
threads = 2

enable-threads = true


http = :9229

vacuum = true
die-on-term = true
harakiri = 200 # close process exceeding this time (seconds)


stats = :21913

logger = file:logfile=Logs/uwsgi.log,maxsize=1000000

This file is a good configuration running flask with uWSGI.

There are several more ways to run flask applications. I will update this post when I can arrange an exciting way about this. Thank you for reading.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.