[mod_python] How to do multi-level dispatch with Vampire

Graham Dumpleton graham.dumpleton at gmail.com
Fri May 4 00:49:33 EDT 2007


On 04/05/07, Jeff Hinrichs - DM&T <jeffh at dundeemt.com> wrote:
> On 5/3/07, Jeff Hinrichs - DM&T <jeffh at dundeemt.com> wrote:
> > On 5/3/07, Graham Dumpleton <graham.dumpleton at gmail.com> wrote:
> > > On 04/05/07, Jeff Hinrichs - DM&T <jeffh at dundeemt.com> wrote:
> > > > with mod_python + vampire what is the proper way to dispatch something like:
> > > >  /jobs/view/7
> > > >
> > > > I'm thinking of this idiom since it is common in some other frameworks,
> > > >
> > > > def _jobs_view(req,path):
> > > >     return 'using _jobs_view'
> > > >
> > > > def _jobs(req, path):
> > > >     d = path.split('/')
> > > >     if d[1] = 'view':
> > > >         return _jobs_view(req, path)
> > > >     else:
> > > >         return 'unknown action'
> > > >
> > > > job = vampire.PathInfo(_jobs)
> > > >
> > > >
> > > > I'm trying to make a RESTful api, i.e. /jobs/view/N, /jobs/edit/N, etc
> > >
> > > From memory and thus untested, but best to use an object instance to
> > > create the URL hierarchy for the 'job/view' component of path, then
> > > use PathInfo wrapper.
> > >
> > >   def _view(req, path):
> > >     return path
> > >
> > >   def Node: pass
> > >
> > >   job = Node()
> > >   job.view = vampire.PathInfo(_view)
> > >
> > > or being more explicit by creating a class for the actual concept.
> > >
> > >   class Job:
> > >     def _view(self, req, path):
> > >       return path
> > >     view = vampire.PathInfo(_view)
> > >
> > >   job = Job()
> > >
> > > If using version of Python with decorators, sure you could come up
> > > with a decorator which allowed you to say:
> > >
> > >   class Job:
> > >     @pass_path_as_argument
> > >     def view(self, req, path):
> > >       return path
> > >
> > > Graham
> > >
> >
> > Graham,
> > That was exactly the nudge I was looking to get.  A little trial and
> > error + some googling resulted in:
> >
> > class Foo:
> >
> >     def __init__(self):
> >
> >         self.bar = vampire.PathInfo(self._bar)
> >
> >         self.baz = vampire.PathInfo(self._baz)
> >
> >     def _bar(self,req,path):
> >
> >         return "foo/bar:%s" % path
> >
> >     def _baz(self,req,path):
> >
> >         return "foo/baz:%s" % path
> >
> >
> >
> > foo = Foo()
> quick question, If I use the class style to handle /foo/bar how do I
> handle a request /foo ?
> I tried creating an def index(self, req) method but that isn't
> working, it also tried def foo(self, req) and Foo.    Or is it not
> possible to create a default method to use when using a class?

Provide a __call__() method.

  class Node: pass

  def _index(req): ...

  foo = Node()
  foo.__call__ = _index

Graham


More information about the Mod_python mailing list