2017-03-19 49 views
0

我使用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 

回答

0

所有你想要的是一個singleton class。將類的實例化限制爲一個對象的類。

Python沒有對單例類的內置支持。但是,你可以使用裝飾器來模仿它。

0

模塊有效地像單身人士。這樣做:

在test_classA.py添加類A的一個實例:

class classA(): 
    print "init class A" 
    varA = {} 

    def __init__(self, subtype): 
     ...etc... 

A = classA() # <-- Add this 

做test_classB.py相似。

然後,在你test_server.py改變你的進口在實例來拉,而不是類:

from test_classA import A 
from test_classB import B 
clsa

而且和clsb做到:

class clsa: 
    ca = A 
    .... 

class clsb: 
    cb = B 
    .... 

這樣,該類將被模塊初始化一次。