0
0
Flaskframework~5 mins

WSGI servers (Gunicorn, uWSGI) in Flask

Choose your learning style9 modes available
Introduction

WSGI servers help your Flask app talk to the internet safely and efficiently. They handle many users at once and keep your app running smoothly.

When you want to run your Flask app on a real web server instead of just testing locally.
When you expect many people to visit your website at the same time.
When you want your app to restart automatically if it crashes.
When you want to improve your app's speed by handling multiple requests at once.
When deploying your Flask app to a cloud or production environment.
Syntax
Flask
gunicorn [OPTIONS] MODULE_NAME:APP_VARIABLE
uwsgi [OPTIONS] --module MODULE_NAME:APP_VARIABLE

MODULE_NAME is the Python file name without .py.

APP_VARIABLE is the Flask app object inside your module.

Examples
This runs Gunicorn with the Flask app named app inside the app.py file.
Flask
gunicorn app:app
This runs uWSGI serving HTTP on port 5000 with the Flask app app inside app.py.
Flask
uwsgi --http :5000 --module app:app
This runs Gunicorn with 4 worker processes to handle multiple requests at the same time.
Flask
gunicorn --workers 4 app:app
Sample Program

This simple Flask app returns a greeting message. You run it with Gunicorn or uWSGI to serve it to users.

Flask
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello from Flask with Gunicorn!'

# To run this app with Gunicorn, save as app.py and run:
# gunicorn app:app

# To run with uWSGI, run:
# uwsgi --http :5000 --module app:app
OutputSuccess
Important Notes

Gunicorn and uWSGI are popular WSGI servers but have different features and configurations.

Always test your app locally with these servers before deploying to production.

Use multiple workers to improve performance but avoid too many to prevent resource overload.

Summary

WSGI servers connect your Flask app to the web and handle many users smoothly.

Gunicorn and uWSGI are common choices for running Flask apps in production.

Use command line options to customize how your app runs with these servers.