Question: It appears to me that Django and Pylons have different ideas on how middleware should work. I like that Pylons follows the standardized [PEP 333](http://www.python.org/dev/peps/pep-0333/), but Django seems to have more widespread adoption. Is it possible to write middleware to be used in both?

The project that involves said middleware is porting a security toolkit called ESAPI from Java to Python. Because Java is so standards oriented, it is pretty easy to be framework agnostic. In Python, different frameworks have different ideas on how basic things like HttpRequest objects and middleware work, so this seems more difficult.

Apparently, new users cannot post more than one hyperlink. See below for links to Django and Pylons middleware info.

Answer: 
Pylons uses standard WSGI middleware. If you deploy Django via WSGI, you can also use WSGI middleware at that point. You can't, however, currently use WSGI middleware via the standard Django MIDDLEWARE\_CLASSES option in settings.py.

That said, there is currently a Google Summer of Code project to enable the use of WSGI middleware in Django itself. I haven't been following the status of this project, but the code is available in the [Http WSGI improvements branch](http://code.djangoproject.com/browser/django/branches/soc2009/http-wsgi-improvements).
For Pylons the term middleware means WSGI ([PEP 333](http://www.python.org/dev/peps/pep-0333/)) middleware, whereas Django means its own internal mechanism for middleware.

However, if you run Django under apache+[mod\_wsgi](http://code.google.com/p/modwsgi/) (instead of e.g. mod\_python or lighttpd+flup) you can also include WSGI middleware in Django. This isn't typically done though because much of the functionality you'll find in WSGI middleware is already built-in to Django proper or Django middleware.

The differences between WSGI and Django middleware are small enough that it should be easy enough to convert code between the two. The tougher problem is when they use external libraries like ORM's.

The [WSGI Wiki](http://www.wsgi.org/wsgi/WsgiStart) has a good list of [WSGI middleware](http://www.wsgi.org/wsgi/Middleware_and_Utilities).