I use a global variable to fit my need:
scores = {}
def update():
global scores
# fetch data from database
scores = xxx
class MyRequestHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
def choice_with_score(items):
# return a key related to scores
return key
def get_key():
global scores
return choice_with_score(scores)
self.write('%s' % get_key())
self.finish()
if __name__ == '__main__':
# initially update
update()
app = tornado.web.Application([
(r'.*', MyRequestHandler),
])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(port)
ioloop = tornado.ioloop.IOLoop.instance()
# background update every x seconds
task = tornado.ioloop.PeriodicCallback(
update,
15 * 1000)
task.start()
ioloop.start()
Here, the function update()
gets new data instead of updating in every incoming request, which is why I use a global variable.
Are there other ways to do the same work?