Proxying every function in a module
Steve Holden
steve at holdenweb.com
Fri May 25 13:30:40 EDT 2007
> Kind and wise fellows,
>
> I've got a web application with the following structure:
>
> 1) module of 100 functions corresponding to user actions (e.g.
> "update_profile()", "organisations_list()")
> 2) a wsgi callable which maps urls to functions eg
> /organisations/list/?sort=date_created is mapped to
> organisations_list("dateCreated")
> 3) mapping is performed using inspect.getargspec()
> 4) a bunch of html generating templates
>
> In the templates I want to generate urls by referencing the function to
> which they map, rather than the url, e.g.
>
> <a href="${organisations_list('dateCreated'})'">Sort By Date Created</a>
>
> In other words, I want to always refer to functions, rather than mixing
> up function calls and urls
>
> I would like a class that proxies all the 100 functions in the user
> actions module. When a proxied function is called via this class it
> should return the url to which it is mapped rather than executing the
> user action function.
>
> <a href="${proxyclass.organisations_list('dateCreated')}">Sort By Date
> Created</a>
>
> should produce:
>
> <a href="/organisations/list/?sort=date_created">Sort By Date Created</a>
>
> Obviously, I don't want to write and maintain copies of these 100
> functions in another class.
>
> My question is therefore: what is the best way to proxy these 100 functions?
>
> Thanks
>
First off, don't attempt to start a new thread by replying to a previous
one. Many newsreaders will merge the two, confusing the hell out of
everyone and generally not helping.
Second, what makes you think you need a module? I'd have thought an
instance of some user-defined class would have been better, as that way
you can redefine the __getattr__() method to return appropriate functions.
This seems to work, though I haven't tested it extensively (i.e. I have
called one instance precisely once ;-)
>>> import re
>>> pat = re.compile("([a-z]+)(.+)")
>>> class myRewriter:
... def srt(self, s):
... m = pat.match(s)
... if not m: raise ValueError(s)
... return m.group(1), m.group(2).lower()
... def __getattr__(self, name):
... n1, n2 = name.split("_")
... def f(val):
... s1, s2 = self.srt(val)
... return "/%s/%s/?sort=%s_%s" % \
... (n1, n2, s1, s2)
... return f
...
>>> r = myRewriter()
>>> r.organisations_list('dateCreated')
'/organisations/list/?sort=date_created'
>>>
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com squidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------
More information about the Python-list
mailing list