Choosing a web server for Python
The built-in server, WSGI, ASGI and the case where you do not need a server at all.
A Python web server can mean three things: the built-in server that shares a folder, a production server such as Gunicorn or Uvicorn that runs your application, or the application framework itself. Which one you need depends on what you are serving.
The short answer
- Files on your own machine:
python -m http.server. Nothing to install. - A web app or API: write it in a framework (Flask, Django, FastAPI) and run it with a production server (Gunicorn for WSGI, Uvicorn for ASGI).
- A site whose pages are the same for every visitor: build it to static files and skip the Python server in production altogether.
The built-in server
python -m http.server 8000
This serves the current folder at http://localhost:8000. It is meant for development and for moving files around, not for the public internet. The options, the Python 2 name and custom handlers are covered in the http.server recipe.
WSGI and ASGI
Python splits "the web server" into two parts with a standard interface between them. The server handles sockets, HTTP parsing and worker processes. The application is your code. Because the interface is standard, any server can run any framework.
WSGI is the original interface, from 2003. The application is a function that takes the request as a dict and returns the response body. One request occupies one worker until it is finished. Flask and Django speak WSGI, and Gunicorn, uWSGI and Waitress are the servers that run them.
ASGI is the async successor. The application is an async function, so one worker can hold thousands of open connections while it waits on databases or other APIs, and it can speak WebSockets. FastAPI and Starlette are ASGI frameworks, Django supports it too, and Uvicorn and Hypercorn are the servers.
You rarely write to either interface by hand. It is still worth seeing once, because every framework is this underneath.
A WSGI app in ten lines
A WSGI application is a callable that takes environ (the request) and start_response (a function to send the status and headers), and returns an iterable of bytes:
def app(environ, start_response):
name = environ["PATH_INFO"].strip("/") or "world"
body = f"Hello, {name}!\n".encode("utf-8")
start_response("200 OK", [
("Content-Type", "text/plain; charset=utf-8"),
("Content-Length", str(len(body))),
])
return [body]
Since it is a plain function, you can call it without any server. The standard library's wsgiref fills in a fake request for you:
from wsgiref.util import setup_testing_defaults
environ = {"PATH_INFO": "/ada"}
setup_testing_defaults(environ)
sent = {}
def start_response(status, headers):
sent["status"] = status
app(environ, start_response) # [b'Hello, ada!\n']
sent["status"] # '200 OK'
That is also how test clients in Flask and Django work: they call the application directly and never open a socket.
To serve it for real, wsgiref includes a reference server:
from wsgiref.simple_server import make_server
with make_server("127.0.0.1", 8000, app) as server:
print("Serving on http://127.0.0.1:8000")
server.serve_forever()
It handles one request at a time and is there for learning and testing. Do not put it on the internet.
Frameworks and production servers
In practice you pick a framework and it hides the interface. A Flask app:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, world!"
flask run starts a development server with reloading and a debugger. For production you run the same app object under Gunicorn, which manages several worker processes and restarts any that die:
gunicorn --workers 4 app:app
A FastAPI app looks similar, with async def handlers and type hints that validate the request for you:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {"message": "Hello, world!"}
It runs under Uvicorn:
uvicorn app:app --host 0.0.0.0 --port 8000
Either way, the usual production setup puts nginx, Caddy or a cloud load balancer in front, to handle HTTPS, static files and slow clients. A rough guide to choosing:
| You are building | Reach for |
|---|---|
| A traditional site with a database | Django with Gunicorn |
| A small app or a few endpoints | Flask with Gunicorn |
| A JSON API, or anything with WebSockets | FastAPI with Uvicorn |
| Docs, a blog, a marketing site | A static site, no app server |
When you do not need a server at all
A lot of sites do not compute anything per visitor. A blog, documentation, a landing page: every visitor gets the same HTML. Running a Python process to hand out the same pages over and over means paying for a server, patching it and restarting it when it falls over, for no benefit.
The alternative is to run Python once, at build time, and publish the output. Nitro CLI does this: pages are Python functions, and the build writes them out as plain HTML files.
nitro new my-site
cd my-site
nitro dev
nitro dev gives you a local server with live reload while you work. nitro build then writes the finished site to a build folder that any static host, bucket or CDN can serve. There is no Python running in production, so nothing to scale or secure beyond the host itself.
This is the wrong fit as soon as pages depend on who is asking: logins, dashboards, a shopping cart, form handling. Those need an application server, and the frameworks above are the answer. Plenty of projects use both: a static site for the public pages and a small API for the parts that need one.
Common questions
Is Flask a web server? No. Flask is a framework that produces a WSGI application. The server is whatever runs it: the built-in development server while you work, Gunicorn or similar in production.
Can I use Gunicorn with FastAPI? Yes. Gunicorn can manage Uvicorn worker processes, which was the standard setup for a long time. Uvicorn's own --workers option now covers most cases without it.
Do I still need nginx in front? If you deploy to a platform that terminates HTTPS and load-balances for you, usually not. On your own server, a reverse proxy is still the normal way to handle certificates, static files and buffering.
Which is faster, WSGI or ASGI? For CPU-bound work, neither; the interface is not the bottleneck. ASGI wins when requests spend most of their time waiting on the network, because one worker can serve many of them at once.
This page uses Nitro CLI.
Build static sites with Python code instead of template engines. Live reload, incremental builds, deploy anywhere.
$ pip install nitro-cli