在webpy中只初始化一次python类

时间:2017-03-19 10:13:02

标签: python python-2.7 web.py

我正在使用webpy来托管一个Web服务,它有两个具有非常繁重的初始化阶段的函数,而且我只想运行一次。 test_server.py包含webpy的main函数,test_classA和test_classB包含两个函数的主要实现。

# 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来测试应用程序......

$ 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

2 个答案:

答案 0 :(得分:0)

你想要的只是一个singleton class。将类的实例化限制为一个对象的类。

Python没有对singleton类的内置支持。但是,您可以使用装饰器来模仿它。

答案 1 :(得分: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

在您的clsaclsb内:

class clsa:
    ca = A
    ....

class clsb:
    cb = B
    ....

这样,该类被模块初始化一次。