繁体   English   中英

使用 Twisted 更新共享数据

[英]Updating shared data with Twisted

如何使用 Twisted 服务器共享数据块,同时在后台定期更新该数据?:

from twisted.internet import reactor
from twisted.internet import task
from twisted.web.server import Site
from twisted.web.resource import Resource

data = 1

def update_data():
    data += 1

class DataPage(Resource):
    isLeaf = True
    def render_GET(self, request):
        return "<html><body>%s</body></html>" % (data, )

root = Resource()
root.putChild("data", DataPage())
factory = Site(root)
reactor.listenTCP(8880, factory)

m = task.LoopingCall(update_data)
m.start(10.0)

print "running"
reactor.run()

由于以下异常,上述代码不起作用:

C:\temp>python discovery.py
Unhandled error in Deferred:
Traceback (most recent call last):
  File "discovery.py", line 23, in <module>
    m.start(10.0)
  File "c:\python25\lib\site-packages\twisted\internet\task.py", line 163, in start
    self()
  File "c:\python25\lib\site-packages\twisted\internet\task.py", line 194, in __call__
    d = defer.maybeDeferred(self.f, *self.a, **self.kw)
--- <exception caught here> ---
  File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 102, in maybeDeferred
    result = f(*args, **kw)
  File "discovery.py", line 10, in update_data
    data += 1
exceptions.UnboundLocalError: local variable 'data' referenced before assignment

我希望 HTTP 客户端访问,在此示例中, http://127.0.0.1:8880/data并检索数据的当前值,同时安排其他一些任务以每隔一段时间更新数据。

此外,我真的不想使用 LoopingCall() 因为我可能想根据更新是否成功来改变间隔; 更新将是某种远程 API 调用。 我可以以某种方式使用 CallLater() 吗?

我敢肯定这是一个愚蠢的问题。 谢谢。

编辑:你帮助正确地使数据变量成为全局变量。 对于接下来的那些,这里是如何将callLater()放入代码中:

from twisted.internet import reactor
from twisted.internet import task
from twisted.web.server import Site
from twisted.web.resource import Resource

data = 1

def update_data():
    global data
    data += 1
    reactor.callLater(10, update_data)

class DataPage(Resource):
    isLeaf = True
    def render_GET(self, request):
        return "<html><body>%s</body></html>" % (data, )

root = Resource()
root.putChild("data", DataPage())
factory = Site(root)
reactor.listenTCP(8880, factory)

update_data()

print "running"
reactor.run()

这段代码仍然感觉有点hacky。 我不喜欢声明模块级变量,更不用说使用全局变量了。 我欢迎任何避免这种做法并使代码看起来更干净和更可重用的建议。

将全局 def 添加到 update_data():

def update_data():
    global data
    data += 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM