Why is a WSGI wrapper required to run Flask with Nginx?

So from the Python / Flask docs, they both recommend not running the Flask webserver as a production webserver, which makes sense. My question is, can I run a Flask application on top of an Nginx server? Why do all the tutorials on the web recommend wrapping Flask around uWSGI, Tornado, or some other WSGI server? What does it mean for something to be WSGI? Isn't Flask WGSI compatible?

I am especially lost because here the first answer reads:

Apache and Nginx are HTTP servers. They can serve static files such as (.jpg and .html files) or dynamic pages (such as a WordPress blog or forum written in PHP or Python).

However, this post reads:

Nginx is a web server. It serves static files, but cannot execute and host a Python application. UWSGI fills this gap.

It just seems inefficient that my application is being processed by a server (like uWSGI) and then by another server (like Nginx).

+5


source to share


2 answers


Nginx is a web server that deals with web server issues, not how to run Python programs. uWSGI is an application server and knows how to speak WSGI with Python (and other languages ​​now). Both Nginx and uWSGI speak the uWSGI protocol, which is an efficient protocol over UNIX sockets.

Nginx deals with http requests / responses to the outside world (maybe load balancing, caching, etc.). Your Flask app deals with WSGI requests / responses. uWSGI knows how to run your application (possibly multiprocessing and / or multithreading) and bridge the gap between HTTP and WSGI.



There are other HTTP servers besides Nginx and other WSGI servers besides uWSGI, but they all use the same workflow: the HTTP server goes to the WSGI server, which manages the application process and goes back to the HTTP server ...

This setting is called a reverse proxy . This allows each tool to do what is good for them without having to worry about other parts of the process. There is nothing particularly ineffective about this until you get to really large scale.

+13


source


Well, WSGI is a specification for the interface between Python applications and web servers. uWSGI (just delivered) an implementation of this specification written in C / C ++. You can run almost any application on a "serious" web server (eg nginx) by simply providing an entry point:

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return ["Hello World"]

      

and then execute it like this:



uwsgi --http :9090 --wsgi-file file_with_the_code_above.py

      

You can return whatever you want instead of ["Hello world"] of course. See http://uwsgi-docs.readthedocs.org/en/latest/WSGIquickstart.html for details .

+1


source







All Articles