twfx
twfx

Reputation: 1694

Initialize a python class only once on webpy

I am using web.py to host a simple web service. The web service runs an analytics application in the backend (inside ClassA). During the initialization of web.py, I'd like to pre-load all data into the memory (i.e call a = ClassA() only once when web server is started), and when the user sends a web request, the web server will just response with the pre-calculated result (i.e return a.do_something).

The code below seems to run init() of class 'add' everytime a HTTP POST request is received. This is a waste of time because the initialization stage takes pretty long. Is it possible to initialize ClassA only once?

import web
from aclass import ClassA

urls = (        
    '/add', 'add'
)

class add:
    def __init__(self):
        a = ClassA()

    def POST(self):
        return a.do_something()

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

Upvotes: 1

Views: 404

Answers (1)

Pit
Pit

Reputation: 4046

Try:

class add:
    a = ClassA()

    def POST(self):
        return add.a.do_something()

This will make it a class-bound parameter instead of a instance-bound one, i.e. only initializing it once.

Upvotes: 2

Related Questions