License New BSD license
Lines 16
Keywords
filter (3) middleware (5) Pylons (10)
Included in this Library
Permissions
Viewable by Everyone
Editable by All Siafoo Users

Change the Base URL of a Pylons App with Middleware Atom Feed 0

In Brief This middleware wraps a Pylons app expecting to be called with a base of '/'. This code lets you specify a base path instead. If requests match the base path, it is stripped off and the modified request is passed to the app. If requests don't match a 404 error is returned (you might have to import from paste.httpexceptions if you are using an older version of Paste).... more
# 's
 1from webob.exc import HTTPNotFound
2
3class FilteredApp(object):
4 '''
5 Only allow access when path_info starts with 'path', otherwise throw 404
6 '''
7 def __init__(self, app, path):
8 self.app = app
9 self.path = path
10
11 def __call__(self, environ, start_response):
12 if self.path and environ['PATH_INFO'].startswith(self.path):
13 environ['PATH_INFO'] = environ['PATH_INFO'][len(self.path):] or '/'
14 environ['SCRIPT_NAME'] += self.path
15 return self.app(environ, start_response)
16 else:
17 raise HTTPNotFound()

This middleware wraps a Pylons app expecting to be called with a base of '/'. This code lets you specify a base path instead. If requests match the base path, it is stripped off and the modified request is passed to the app. If requests don't match a 404 error is returned (you might have to import from paste.httpexceptions if you are using an older version of Paste).

You can wrap your app with this in your middleware.py with:

# 's
1app = FilteredApp('/new/path')

Since this cod returns 404 for anything that doesn't match the path, you probably want another app to fall back to, using paste.cascade.Cascade. This middleware was actually written to give a new base url to Paste's StaticURLParser:

# 's
1static_app = StaticURLParser(os.path.join(config['pylons.paths']['static_files'], '/new/path'))
2if base_url:
3 static_app = FilteredApp(static_app, base_url)
4
5app = Cascade([static_app, app])