HTTP Server to Python script
While there are many tutorials how to setup NGINX with uWSGI or gunicorn and Python code, almost none of them give an overview how request goes from NGINX to Python.
Input
- NGINX listens to TCP port.
- Client opens connection and sends HTTP request.
- NGINX accepts connection and parses request.
Request within NGINX
NGINX decides, accorting to configuration, what to do with request. It can:
- Respond on its own, if it is request for static data, redirection or erroneous request. NGINX can ignore request completely closing connection without any data sent back; it’s done by specifying
return 444
. - Transform and pass request further to
- uWSGI —
uwsgi_pass
directive, - gunicorn —
proxy_pass
directive, - other upstream —
proxy_pass
,fastcgi_pass
,scgi_pass
andmemcached_pass
directives.
- uWSGI —
uWSGI
- uWSGI listens to TCP port or Unix socket. (Latter is preferred because of performance.)
- NGINX sends request formed accroding to binary uwsgi protocol. first byte of request packet header,
modifier1
, is0
. - uWSGI accepts it and calls Python script.
uwsgi protocol documentation also supports other types of requests, not only WSGI; it’s defined by first byte of request packet header, modifier1
.
Configuring NGINX to pass requests to uWSGI.
gunicorn
- gunicorn listens to TCP port or Unix socket. (Latter is preferred because of performance.)
- NGINX sends (possibly modified) HTTP request.
- gunicorn accepts it and calls Python script.
Configuring NGINX to pass requests to gunicorn.
Python script
CPython provides binary API to call Python callables from native, binary code. That’s why uWSGI works specifically with CPython. Other interpreters, specifically PyPy and Jython, are supported individually.