Introducing WSGI

Python web applications were originally written against these CGI and FastCGI protocols, and a now mostly defunct mod_python Apache module. This proved troublesome, though, since Python web applications were tied to the protocol or server they had been written for. Moving them to a different server or protocol required some reworking of the application code.

This problem was solved with PEP 333, which defined the WSGI protocol. This established a common calling convention for web servers to invoke web application code, similar to CGI. When web servers and web applications both support WSGI, servers and applications can be exchanged with ease. WSGI support has been added to many modern web servers and is nowadays the main method of hosting Python applications on the web. It was updated for Python 3 in PEP 3333.

Many of the web frameworks we discussed earlier support WSGI behind the scenes to communicate with their hosting web servers, Flask and Django included. This is another big benefit to using such a framework – you get full WSGI compatibility for free.

There are two ways a web server can use WSGI to host a web application. First, it can directly support hosting WSGI applications. Pure Python servers such as Gunicorn follow this approach, and they make serving Python web applications very easy. This is becoming a very popular way to host Python web applications.

The second approach is for a non-Python server to use an adapter plugin, such as Apache's mod_wsgi, or the mod_wsgi plugin for Nginx.

The exception to the WSGI revolution is event-driven servers. WSGI doesn't include a mechanism to allow a web application to pass control back to the calling process, and so there is no benefit to using an event-driven server with a blocking-IO style WSGI web application because as soon as the application blocks for database access, for example, it will block the whole web server process.

Hence, most event-driven frameworks include a production-ready web server. Making the web application itself event-driven and embedding it in the web server process is really the only way to host it. To host web applications with these frameworks, check out the framework's documentation. In this chapter, we will review specific frameworks such as Django and Flask.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset