Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does running Flask with Nginx require a WSGI wrapper?

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

I am particularly lost because here, the first response states:

Apache and Nginx are both HTTP servers.They can serve static files like (.jpg and .html files) or dynamic pages (like a Wordpress blog or forum written in a language like PHP or Python).

However this post states:

Nginx is a web server. It serves static files, however it cannot execute and host Python application. uWSGI fills that gap.

It just seems inefficient for my application to be handled by a server (ex: uWSGI) and then another server (ex: Nginx).

like image 395
Steven K Avatar asked Nov 19 '14 06:11

Steven K


1 Answers

Nginx is a web server and is concerned with web server stuff, not with 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 from/responses to the outside world (possibly load balancing, caching, etc.). Your Flask application deals with WSGI requests/responses. uWSGI knows how to start your application (possibly with multiprocessing and/or threading) 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 passes to the WSGI server, which manages your application process and passes back to the HTTP server.

This setup is known as a reverse proxy. It allows each tool to do what it's good at and not be concerned about the other parts of the process. There is nothing particularly inefficient about it, until you get to truly massive scales.

like image 199
davidism Avatar answered Oct 13 '22 14:10

davidism