Learning Python Network Programming

(Sean Pound) #1

Applications for the Web


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,
hence 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 example, for
database access, 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.


Hosting in practice


So how does this all work in practice? Well as we saw with Flask, many frameworks
come with their own built-in development web servers. However, these are not
recommended for use in a production environment as they're generally not designed
to be used where security and scalability are important.


Currently, probably the quickest way to host a Python web application with a
production quality server is with the Gunicorn server. Using our Flask application from
earlier, we can get it up and running using just a few steps. First we install Gunicorn:


$ pip install gunicorn


Next we need to slightly modify our Flask app so that it's use of builtins
works correctly under Gunicorn. In your tinyflaskapp.py file, find the line:


objs = __builtins__.__dict__.items()

Change it to:


objs = __builtins__.items()

Now we can run Gunicorn. From within your Flask application project folder, run
the following command:


$ gunicorn --bind 0.0.0.0:5000 tinyflaskapp:app


This will launch the Gunicorn web server, listening on port 5000 on all available
interfaces and serving our Flask application. If we now visit it in a web browser via
http://127.0.0.1:5000, we should see our documentation index page. There are
instructions to daemonize Gunicorn, so that it runs in the background and starts
and stops automatically with the system, available in the documentation pages at
http://gunicorn-docs.readthedocs.org/en/latest/deploy.html#monitoring.

Free download pdf