[mod_python] How to use Classes

Graham Dumpleton grahamd at dscpl.com.au
Sat Jul 15 18:13:00 EDT 2006


On 15/07/2006, at 11:55 PM, Sanjeev Divekar wrote:

> Hi guys
>
> How can i use Classes in mod_python.
> ********************************************************************** 
> ***
> class myclass:
>    def __init__():
>        return "Hello"
>
>    def index(req,para=''):
>        tmpl = psp.PSP(req, filename='a.html')
>        tmpl.run(vars={'para':para})
>        return
>
>    def show_data(req, para):
>        msg = "Your first name is " + para[0]
>        index(req, para=msg)
>        return
> ********************************************************************** 
> ***
> Any good documentation/ebook/sample app on mod_pythong

Ensuring you are using mod_python 3.2.8 or later, you can rewrite the
above sort of like the following.

class myclass:

    def _index(req,para=''):
        tmpl = psp.PSP(req, filename='a.html')
        tmpl.run(vars={'para':para})

    def __call_(req,para=""):
        self._index(req,para)

    def show_data(req, para):
        msg = "Your first name is " + para[0]
        self._index(req, para=msg)

   index = myclass()

Now, it is a bit unclear from your code what you actually expected  
to  be called
so to explain briefly.

1. Your code seemed to be tailored to using mod_python.publisher, so you
must be using that in example I present.

2. You must use mod_python 3.2.8 or later as earlier versions can  
complain
if None is returned from function.

3. You must actually create an instance of your class. Here I have  
named the
instance of the class "index" so that that is where the default URL  
will match.

Thus if this was in file "example.py", the URL 'example.py' would  
invoke the
__call__() method. In other words, the class instance must be a  
callable object.

If the URL is 'example.py/show_data', then the 'show_data()' method  
is called
instead.

4. I couldn't map your originally constructor to anything as not  
clear when
you expected it to be called.

In short, you need to create an instance of the class and once you  
have done
that URLs will magically map to member variables and member functions of
the class instance. If you want something to be hidden, you should  
prefix the
name of it with an underscore. Exception is '__call__()' method which  
is special
and applied when URL is mapped to object instance itself.

Go back and review the mod_python.publisher documentation on the
mod_python web site and see if it makes more sense now.

Graham







More information about the Mod_python mailing list