django's view.py as class not just methods
Rob Wolfe
rwNOSPAM at NOSPAMsmsnet.pl
Fri Aug 25 14:47:15 EDT 2006
Skink <spam at me.please> writes:
> Hi,
>
> I'm relatively new to django and maybe my question is stupid, but...
>
> Is it possible to map in urls.py some url not to function in views.py
> (which has first argument with HttpRequest) but to some class method?
> In that case each instance of such class would be created when session
> starts and for subsequent calls would be served as self ?
>
> I know, I know that HttpRequest has session member and I can use it.
> But maybe it would be good idea to have such url ==> class.method
> mapping.
I didn't try it with django but maybe closure is the solution.
Try this:
<code>
#!/usr/bin/env python
class MyView(object):
def __init__(self):
self.visited = []
def index(self, *args):
self.visited.append("index")
print "%s.index: %r" % (self.__class__.__name__, args)
return "response from index"
def detail(self, *args):
self.visited.append("detail")
print "%s.detail: %r" % (self.__class__.__name__, args)
return "response from detail"
def error(self, *args):
self.visited.append("error")
print "%s.error: %r" % (self.__class__.__name__, args)
return "response from error"
def make_view(obj, methodname):
def view(*args):
try:
return getattr(obj, methodname)(*args)
except AttributeError:
return obj.error(*args)
return view
view_obj = MyView()
index = make_view(view_obj, "index")
detail = make_view(view_obj, "detail")
download = make_view(view_obj, "download")
print index("request to index")
print detail("request to detail", 25)
print download("request to download", "abc", 99)
print
print "\n".join(view_obj.visited)
</code>
index, detail and download functions can be mapped
in urls.py now.
--
HTH,
Rob
More information about the Python-list
mailing list