我使用webpy託管一個具有兩個函數的Web服務,這兩個函數的初始化階段非常繁重,而且我只想運行一次。 test_server.py包含webpy的主函數,test_classA和test_classB包含兩個函數的主要實現。在webpy中只初始化python類一次
# test_server.py
import web
from test_classA import classA
from test_classB import classB
urls = (
'/clsa', 'clsa',
'/clsb', 'clsb',
)
class clsa:
ca = classA('subtype1')
def __init__(self):
self.ca.dosomething('subtype1')
def POST(self):
self.ca.doanotherthing()
class clsb:
cb = classB()
def POST(self):
self.cb.dosomething()
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
# test_classA.py
class classA():
print "init class A"
varA = {}
def __init__(self, subtype):
"""a very heavy-loaded function that read a lot of data into memory"""
print "init class A instance, subtype:", subtype
def dosomething(self, subtype):
print "class A do something for " + subtype
self.varA['apple'] = 1
def doanotherthing(self):
print "class A do another thing"
self.varA['orange'] = 2
print self.varA
# test_classB.py
class classB():
print "init class B"
varB = {}
def __init__(self):
"""a very heavy-loaded function that read a lot of data into memory"""
print "init class B instance"
def dosomething(self):
print "class B do something"
我用捲曲來測試應用程序...
$ curl localhost:8084/clsb --data-binary "hello"
None$ curl localhost:8084/clsa --data-binary "hello"
None$ curl localhost:8084/clsb --data-binary "hello"
我也得到使用curl命令如下...
$ python test_server.py 8084
init class A
init class B
init class A instance, subtype: subtype1
init class B instance
http://0.0.0.0:8084/
init class A instance, subtype: subtype1
init class B instance
class B do something
127.0.0.1:50760 - - [19/Mar/2017 20:03:08] "HTTP/1.1 POST /clsb" - 200 OK
class A do something for subtype1
class A do another thing
{'orange': 2, 'apple': 1}
127.0.0.1:50780 - - [19/Mar/2017 20:03:17] "HTTP/1.1 POST /clsa" - 200 OK
class B do something
127.0.0.1:50786 - - [19/Mar/2017 20:03:32] "HTTP/1.1 POST /clsb" - 200 OK
我的問題是,我怎麼能初始化ClassA和ClassB的只有一次。即,我得到以下日誌只有一次,無論在第一或第二捲曲命令發送..
>>> init class A instance, subtype: subtype1
>>> init class B instance