Updating Shared Data Using Twisted

How can I exchange a data block using a Twisted server, and while periodically updating this data in the background ?:

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()

The above code does not work due to the following exception:

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

I would like HTTP clients in this example to get http://127.0.0.1:8880/data and retrieve the current value of the data, at the same time there is another task planned to update the data regularly.

Also, I really don't want to use LoopingCall (), because I can change the interval depending on whether this update is successful or not; the update will be a kind of remote API call. Can I use CallLater () in some way?

I am sure this is a stupid question! Thank.

: . , , 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()

- . , . , .

+3
1

def update_data():

def update_data():
    global data
    data += 1
+2

All Articles