Python Tornado更新请求之间的共享数据

迈克·C

我有一个Python Tornado应用程序。该应用程序包含请求处理程序,为此我向其传递数据(下面的代码并不完整,仅用于说明我想要的内容):

configs = {'some_data': 1, # etc.
          }

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [('/pageone', PageOneHandler, configs),
                    ('/pagetwo', PageTwoHandler, configs)]
        settings = dict(template_path='/templates',
                    static_path='/static', debug=False)
        tornado.web.Application.__init__(self, handlers, **settings)

# Run the instance
# ... code goes here ...
application = Application()
http_server = tornado.httpserver.HTTPServer(application)
# ... other code (bind to port, etc.)

# Callback function to update configs
some_time_period = 1000 # Once an second
tornado.ioloop.PeriodicCallback(update_configs, some_time_period).start()
tornado.ioloop.IOLoop.instance().start()

我希望update_configs函数更新configs上面定义变量,并使此更改通过处理程序传播。例如(我知道这行不通):

def update_configs():
    configs['some_data'] += 1

# Now, assuming PageOneHandler just prints out configs['some_data'], I'd expect
# the output to be: "1" on the first load, "2" if I load the page a second
# later, "4" if I load the page two seconds after that, etc.

问题是,configsApplication的构造函数中创建过程中变量将传递给处理程序如何configs['some_data']在定期回调函数中更新

这种机制的实际用例是configs每隔一段时间从数据库刷新一次字典中存储的数据

有没有一种简单的方法可以做到这一点而又不摆弄application.handlers(我在过去一个小时左右的时间里一直在尝试)?

损伤

好吧,最简单的方法是将整个config dict传递给处理程序,而不只是将dict中的单个值传递给处理程序。由于字典是可变的,因此您对字典中的值所做的任何更改都将传播到所有处理程序:

import tornado.web
import tornado.httpserver

configs = {'some_data': 1, # etc.
          }

def update_configs():
    print("updating")
    configs['some_data'] += 1

class PageOneHandler(tornado.web.RequestHandler):
    def initialize(self, configs):
        self.configs = configs
    def get(self):
        self.write(str(self.configs) + "\n")


class PageTwoHandler(tornado.web.RequestHandler):
    def initialize(self, configs):
        self.configs = configs

    def get(self):
        self.write(str(self.configs) + "\n")


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [('/pageone', PageOneHandler, {'configs' : configs}),
                ('/pagetwo', PageTwoHandler, {'configs': configs})]
        settings = dict(template_path='/templates',
                    static_path='/static', debug=False)
        tornado.web.Application.__init__(self, handlers, **settings)

# Run the instance
application = Application()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)

# Callback function to update configs
some_time_period = 1000 # Once an second
tornado.ioloop.PeriodicCallback(update_configs, some_time_period).start()
tornado.ioloop.IOLoop.instance().start()

输出:

dan@dantop:~> curl localhost:8888/pageone
{'some_data': 2}
dan@dantop:~> curl localhost:8888/pageone
{'some_data': 3}
dan@dantop:~> curl localhost:8888/pagetwo
{'some_data': 4}
dan@dantop:~> curl localhost:8888/pageone
{'some_data': 4}

对我来说,这种方法最有意义。包含的数据configs实际上并不属于a的任何一个实例RequestHandler,它是所有RequsetHandlers以及您的共享的全局状态PeriodicCallback因此,我认为尝试创建该状态的X份副本,然后尝试使所有这些不同的副本手动保持同步是没有意义的。相反,只需使用带有类变量的自定义对象或字典来共享整个过程的状态,如上所示。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章