12

I have the following use case for my Tornado web server:

Upon POST requests entries can be made to the server, entries which will not be persisted to a file or database. Upon GET requests a process can be started or terminated.

Hence I need to share data between different requests in my RequestHandler implementation. What is the normal way to do so?

I had difficulties saving data to self, for instance self.entry = "...". In another request the data was not present anymore.

The only working solution I've found is to store that in the application object:

    application = web.Application([
            (r'.*', MainHandler,
            ])

and

    def get(self):
         # ...
         self.application.entry = "..."

Is that the proper way? Also what about synchronization here, I mean this means access to shared data.

4

4 回答 4

17

我建议如下:而不是数据库访问对象传递一个存储您的数据的对象,例如:

data = DataStore()

application = web.Application([
        (r'.*', MainHandler, dict(data = data),
        ])

使用以下RequestHandler初始化方法。

def initialize(self, data):
     self.data = data

您必须在之前创建对象并传递它,否则每次处理请求时都会重新创建它。

于 2012-09-03T11:32:58.583 回答
6

文档提供了一种方法来做到这一点:

class MyHandler(RequestHandler):
    def initialize(self, database):
        self.database = database

    def get(self, username):
        ...

mydatabase = dict()

app = Application([
    (r'/user/(.*)', MyHandler, dict(database=mydatabase)),
    ])

然后,您可以将对象保存mydatabase到文件中。

但我不确定这是实现请求之间同步的正确方法。

于 2012-09-03T07:20:12.827 回答
1

你可以使用memcached这样的东西。但是,您需要设置 memcached 服务器。

http://pypi.python.org/pypi/python-memcached/

于 2012-09-03T05:31:38.860 回答
1

应用程序是存储(半)持久数据的正确对象。但是,正如其他 anwser 所建议的那样,您应该考虑使用某种数据库来存储这些数据。

但是,您应该注意如果会话(或事务)没有正确完成(例如,您得到一个 POST 但没有 GET 来触发该操作),您应该删除会话数据,以免您的网络服务器泄漏内存。

根据我的经验,我建议使用Redis,因为它易于使用并支持密钥过期,当您需要管理会话数据时,这种机制会派上用场。

于 2012-09-03T06:43:25.027 回答