The Standardized Web: Decoupling Python with WSGI and PEP 333
In the first half of 2007, Python web development is finally escaping its 'silo' problem. If you wanted to run a Python app in 2003, you had to choose between mod_python, FastCGI, or a custom server specific to your framework (Zope, anyone?). Moving an app from one server to another was a Herculean task.
Phillip J. Eby’s PEP 333, the Web Server Gateway Interface (WSGI), has changed all that. It’s a simple, elegant specification that defines how a web server talks to a Python application. It’s our 'universal adapter'.
The WSGI Application Interface
At its core, a WSGI application is just a 'callable' (a function or a class with a __call__ method). It takes two arguments: environ (the CGI-style environment) and start_response (a callback to send HTTP headers).
def simple_app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'text/plain')]
# Send the headers to the server
start_response(status, headers)
# Return an iterable (the body)
return ["Hello, 2007-style WSGI World!".encode('utf-8')]
The Middleware Revolution
Because WSGI is so simple, we can wrap applications in 'middleware'. This allows us to intercept the request or response to add functionality like authentication, Gzip compression, or session management without the application even knowing it.
class UpperCaseMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
for response in self.app(environ, start_response):
yield response.upper()
Django 0.96 and the Future
With the rise of Django (currently at version 0.96), we're seeing the first 'killer app' for WSGI. Django allows us to build complex, database-driven sites in days instead of weeks. And thanks to WSGI, we can deploy Django on anything from Apache with mod_wsgi to the newer, lightweight gunicorn.
Django's 'MTV' (Model-Template-View) pattern is a refinement of the MVC we've seen in other frameworks. It treats the 'Admin Interface' as a first-class citizen, which is revolutionary. In 2007, being a Python web developer means thinking in terms of reusable apps and clean, standardized interfaces.
The overhead of mod_python is being left behind. We're moving toward a world where the server (Apache, Nginx, Cherokee) and the application (Django, Pylons, TurboGears) are completely decoupled. This is how we build infrastructure that scales.
Aunimeda builds production-grade backend systems - APIs, microservices, real-time applications, and system integrations.
Contact us for backend engineering services. See also: Custom Software Development, Web Development