Hide
Solve a problem – Filter by language, license, keyword, owner, or search text to find code & info fast. Join Siafoo Now or Learn More

Make a Pylons App Middleware for Another Atom Feed 0

In Brief Use this class to set up your Pylons app as middlware for another. The middleware app will take over at a certain base URL and show its interface, but feel free to do something different. You can probably get the base_url from the config directly, but we pass it separately for clarity here.... more
# 's
 1import pylons
2from paste.deploy import loadapp
3
4class MyMiddleware(object):
5 def __init__(self, app, config, base_url):
6 self.app = app
7
8 self.middleware_app = loadapp('config:%s' % config['__file__'], name='middleware_app')
9 self.base_url = base_url
10
11 # Remove the config from the config stack; otherwise the host app gets *very* confused
12 # We should be done initializing the middleware app, so this isn't used again anyways.
13 # The RegistryMiddleware takes care of this from now on (during requests).
14
15 process_configs = pylons.config._process_configs
16 this_conf = [conf for conf in process_configs if conf['pylons.package'] == 'name_of_my_middleware_package'][0]
17 process_configs.remove(adjector_dict)
18
19 def __call__(self, environ, start_response):
20 if self.base_url and environ['PATH_INFO'].startswith(self.base_url):
21 environ['PATH_INFO'] = environ['PATH_INFO'][len(self.base_url):] or '/'
22 environ['SCRIPT_NAME'] = self.base_url
23 return self.adjector_app(environ, start_response)
24
25 else:
26 return self.app(environ, start_response)

Use this class to set up your Pylons app as middlware for another. The middleware app will take over at a certain base URL and show its interface, but feel free to do something different. You can probably get the base_url from the config directly, but we pass it separately for clarity here.

This script olves a problem where Pylons effectively overwrites configuration values for your host application when the middleware is initialized. That is fixed (read:hacked) with the last three lines in __init__ here. For details see Pylons Tips, Tricks, and Hacks.

To install this, you want to add this line in your middleware.py, between the cache middleware and the error middleware (where presumably all your custom middlware is):

# 's
1app = MyMiddleware(app, config, base_url = '/some/base/url'

Add a [app:middleware_app] stanza to your host app's .ini file with any configuration options for the middleware app.