簡體   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