Named groups in URL mappings regexp

10 views
Skip to first unread message

Tito Costa

unread,
Mar 29, 2009, 5:46:05 PM3/29/09
to Google App Engine
I would like to use named groups in the regular expressions passed on
to the webapp.WSGIApplication constructor.
The main reason is that I need to pass HTTP parameters embedded in the
URL in a different order than the positional parameters in the
corresponding get() method of the RequestHandler class.

Example:
web_application = webapp.WSGIApplication([
(r"/xhtml/(?P<output>[^/]+)/wall/(?P<user_key>[^/]+)",
messaging.WallPage),
])

The output parameter represent the format of the page.
The user_key parameter is an identifier for a particular application
user.

The signature of the get method of the RequestHandler WallPage would
be the following:
def get(self,user_key, output="iphone")

Even though I'm using named groups in the URL mapping, regexp matching
groups are always passed as positional parameters to the get method,
so they end up being swapped.

Is it simply not supported or am I doing something wrong?

Thank you

molicule

unread,
Mar 30, 2009, 6:13:36 AM3/30/09
to Google App Engine
Hi,

You need to change WSGIApplication.wsgi_call to support this.
Here is what I'm doing
1. create a new file gapngo/wsgi.py, like so
#!/usr/bin/env python
#

from google.appengine.ext.webapp import *
from google.appengine.ext.webapp.util import run_wsgi_app

def wsgi_call(self, environ, start_response):
"""Called by WSGI when a request comes in."""
request = Request(environ)
response = Response()

# placeholder for middleware
request.blue = "blue"

WSGIApplication.active_instance = self

handler = None
groups = ()
for regexp, handler_class in self._url_mapping:
match = regexp.match(request.path)
if match:
handler = handler_class()
handler.initialize(request, response)
groups = match.groups()
kwargs = match.groupdict()
break

self.current_request_args = groups

if handler:
try:
method = environ['REQUEST_METHOD']
if method == 'GET':
handler.get(*groups, **kwargs)
elif method == 'POST':
handler.post(*groups, **kwargs)
elif method == 'HEAD':
handler.head(*groups, **kwargs)
elif method == 'OPTIONS':
handler.options(*groups, **kwargs)
elif method == 'PUT':
handler.put(*groups, **kwargs)
elif method == 'DELETE':
handler.delete(*groups, **kwargs)
elif method == 'TRACE':
handler.trace(*groups, **kwargs)
else:
handler.error(501)
except Exception, e:
handler.handle_exception(e, self.__debug)
else:
response.set_status(404)

response.wsgi_write(start_response)
return ['']

def run_gapngo_app(application):
WSGIApplication.__call__ = wsgi_call
run_wsgi_app(application)

2. In your views make the following changes
import gapngo.wsgi as wsgi
.....
def get(self, *args, **kwargs):
.....
wsgi.run_gapngo_app(application)

3. Now access your named regex groups as kwargs.get("blah")

Also note there is a placeholder for calling middleware.

S. Sriram
Reply all
Reply to author
Forward
0 new messages