Custom URLParser for Webware

Yes it works !!
While looking for a way to have some better URL in Webware, than the defaut http://host/Servlet?arg0=..&arg1=, Ian tell me to look at WebKit.URLParser. After a little time looking at the source i managed to do this without too much pain. As i can’t find example on the web, I put this here, if Ian is ok, i will perhaps post this on the wiki.

# put this in your context __init__.py file

class CustomParser(URLParser.URLParser):
"""
Class to do the dispatch of Request it should return a servlet instance
if we return nothing the default Webware behaviour is used
"""

def parse(self,trans,requestPath):
values=string.split(requestPath,'/')

if values[-2] == 'Article':
restPart = '/'
name = 'blog/Article.py'

req = trans.request()
req.setField('id',values[-1])

req._extraURLPath = restPart
req._serverSidePath = name
return URLParser.ServletFactoryManager.servletForFile(trans, name)

# we use the default url handling
return None

urlParser=CustomParser()

So now url like http://alias.larsen-b.com/Article/1 will map to the servlet Article.py and argument id=1 (http://alias.larsen-b.com/Article?id=1).
Of course this is a really simple example, but you can do things really more funny.



Related Posts

5 thoughts on “Custom URLParser for Webware

  1. Interestingly, it seems like this will map any URL ending in Article/X to blog/Article?id=X.  So /really/long/URL/to/Article/10 will map to the same location as /Article/10.  Which is, perhaps, what you want.

    You can raise exceptions in the parsing too, so you could do something like (after you tests for ‘Articles’):

    if len(values) != 3:

    ….# I think it should be 3, including the empty root segment, but maybe the magic number is 2

    ….raise HTTPRedirect(location=’/Article/%s’ % values[-1])

    Then you’ll accept alternate URLs, but canonicalize them to a single form.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>