Latest Version: 0.9.6.2
  Dashboard > Pylons Cookbook > ... > Recipes > Adding your own middleware
  Pylons Cookbook Log In | Sign Up   View a printable version of the current page.  
  Adding your own middleware
Added by Christoph Haas, last edited by Ches Martin on Dec 09, 2007  (view change) show comment
Labels: 
(None)

Note: additional info on WSGI and middleware in Pylons can be found in the document Web Server Gateway Interface Support.

Adding your own middleware

As Ian Bicking (creator of "Paste") said: "Middleware is where people get a little intimidated by WSGI and Paste." But if you understand the very basics of WSGI and how the actual HTTP request is passed around it is not that scaring any more. A good introduction is given by Ian's A Do-It-Yourself Framework article.

A very simple piece of middleware:

1
2
3
4
5
6
class MyMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        return ['This request passed through MyMiddleware'] + self.app(environ, start_response)

This will prepend all pages that are sent to the browser with the sentence "This request passed through MyMiddleware". To plug into your application just add the following line in your middleware.py where it reads "Put your own middleware here":

1
app = MyMiddleware(app)

(Re-)Start your application and request a URL. You should see your sentence at the top.

Of course this is just a Hello-World-style example. There are much better uses for middleware. Check out the section on middleware in Ian's article for more information.

Site running on a free Atlassian Confluence Open Source Project License granted to Pylons. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.3.3 Build:#645 Feb 13, 2007) - Bug/feature request - Contact Administrators
Top