Repository navigation
SmartUrl
Application filters provide a very powerful and flexible way of customizing the way Karrigell manages requests.
This HowTo (written by Jim Eggleston) shows how it can be used to manage "smart urls" ; let's take the example of a Wiki application where we want urls like http://kswiki/index.py/show/MyWikiPage.
Basically Karrigell would return a 404 Not found error. However it can be made to work using an app filter.
This is a sample server.py :
import urllib.parse
import Karrigell
class ktwiki(Karrigell.App):
def ktwiki_filter(self,handler):
pth = handler.path_info
parts = urllib.parse.unquote(pth).split('/')
if len(parts) < 5:
return None # normal URL, no processing required
newpth = '/'.join(parts[:-1])
handler.body['pageName'] = parts[-1]
return handler.get_file(newpth)
filters = [ktwiki_filter]
Karrigell.run(apps=[ktwiki]) This is what is happening, firstly at a high level, then in more detail.
ktwiki_filter is the filter method. You have to tell Karrigell what the filter functions are for your app by assigning a list of methods to the the filters attribute of the app class (ktwiki in this case.) The Karrigell request handler will call each filter function for the app after it has parsed the URL but before attempts to process it.
Looking at the filter method ktwiki_filter, you will see it takes the parameter handler, that is, the request handler object. The handler object holds the data and methods required to process requests. It is the handler object that we will be manipulating.
To handle a URL like /ktwiki/index.py/show/MyWikiPage, MyWikiPage has to be trimmed off the end. MyWikiPage has to be put somewhere where the show() function in index.py can get to it.
Ok, now I'll step through ktwiki_filter:
First I get the URL passed to Karrigell:
pth = handler.path_infoThen I unquote it and split it into parts:
parts = urllib.parse.unquote(pth).split('/')In this application, if there are less than 5 parts, then no
processing is required. Return None and let Karrigell handle the URL.
if len(parts) < 5:
return None # normal URL, no processing requiredThe new path consists of the first four elements:
newpth = '/'.join(parts[:-1])The last part of the URL is the Wiki page name. This needs to be
passed to the show() function. Parameters passed to functions are held
as key/value pairs in the request body (handler.body) so that's where
we'll save the page name:
handler.body['pageName'] = parts[-1]Finally we return the physical path of the resource. I am using the
get_file() method of the handler object to do the work:
return handler.get_file(newpth)The show() function in index.py looks like this. It will receive "pageName" as a parameter:
def show(pageName=None):
if pageName is None:
# raise exception
# Process page ...