|
Graham Dumpleton
grahamd at dscpl.com.au
Tue Dec 6 17:53:58 EST 2005
Going back to your original email ....
Radek =?iso-8859-2?q?Barto=F2?= wrote ..
> Hello.
> I like using mod_python's mod_python.publisher like this:
>
> class MyClass:
> def __init__(self):
> # can I get request object here?
> ...
> def __str__(self):
> ...
> def method1(self, req):
> ...
> def method2(self, req):
> ...
>
> # or can I get request object here and pass it to MyClass's constructor?
> index = MyClass():
> ...
If what it is that you want is that an instance of MyClass be created
specific for each request, before any URL mapping against methods is
being done, then using mod_python.publisher alone the answer is that no
it cannot be done easily. Unless my brain is overlooking something
obvious, you have to do something convoluted like:
from mod_python import util, apache
import types
class Wrapper:
def __init__(self,function):
self.__class = function.im_class
self.__name = function.im_func.__name__
def __call__(self,req):
instance = self.__class(req)
function = getattr(instance,self.__name)
return util.apply_fs_data(function,req.form)
class MyClass:
def __init__(self,req):
self.__req = req
def method1(self):
return "method1"
def method2(self):
return "method2"
class Object: pass
index = Object()
index.method1 = Wrapper(MyClass.method1)
index.method2 = Wrapper(MyClass.method2)
Apart from that, if you were using Vampire, you could simply use basic
handlers are write:
import vampire
class MyClass:
def __init__(self,req):
self.__req = req
def __call__(self):
return "__call__"
def method1(self):
return "method1",self.__req.filename
def method2(self, req):
return "method2",req.filename
handler = vampire.Publisher(MyClass)
The vampire.Publisher() wrapper class handlers both creating an instance
of the class and mapping URLs onto methods of the instance. It only
supports callable methods in classes though. Ie., it will not map URLs
to __str__() or to basic data types which are a member of the class.
Note that creating an instance of a class per request could be quite
inefficient. What is the original reason that you wanted to access the
request object in the constructor in the first place?
Graham
|