On Jun 29, 2010, at 7:38 PM, Tejaswi wrote:

> I have the following code that does a simple hello wolrd app using
> webpy. For each call to the GET method, the class Dashboards
> "__init__" method gets called. Is there a way to change the behavior
> to let __init__ be called only once? I have some expensive setup
> methods in __init__ and I don't want them getting called for each call
> to GET.
> 
> import web
> urls = ('/', 'Dashboard')
> web.config.debug = False
> app = web.application(urls, globals())
> class Dashboard:
>    def __init__(self):
>        # Add other init methods here
>        print "Should be printed only once"
> 
>    def GET(self):
>        return "Hello world!"
> 
> if __name__ == "__main__":
>    app.run()
> 
> I am sure there is something rudimentary that I am missing. Hope
> someone here can help me. I tried searching on the groups and on the
> webpy site for info. But no luck still.


The reason that __init__ is called multiple times is that at least 
conceptually, a new instance of your Python script is run for each web page 
retrieved.  IOW, when the web server receives a request for a page, your 
application is started up and passed parameters and environment variables. Your 
application takes this data an creates an output web page that is returned to 
the web server and your application terminates.  This is what happens when your 
application is run as a CGI (common gateway interface) program with an external 
web server, such as apache.

If you are using webpy's built in server, the server portion stays running. You 
could modify the server code (it's also written in Python) to do your 
initialization; however, that would not work if you migrated your application 
to another web server.

You could look into webpy's session support, but that's really designed to keep 
persistent information for a given user and it sounds like you want persistent 
information for multiple users.

Here's a suggestion:  Have the program calculate the expensive information and 
save it to a file, perhaps using Python's pickle method. Then each time the web 
page is retrieved, the __init__ would only load the pre computed data.  You 
could time stamp the data so that it would expire periodically and have to be 
re-computed.

Mark

-- 
You received this message because you are subscribed to the Google Groups 
"web.py" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/webpy?hl=en.

Reply via email to