简体   繁体   中英

How to share data between requests in Tornado Web

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.

I suggest the following: Instead of a database access object pass an object which stores your data, for instance:

data = DataStore()

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

with the following RequestHandler initialization method.

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

You have to create the object before and pass it, otherwise it will be recreated every time a request is processed.

The documentation gives a way to do this :

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

    def get(self, username):
        ...

mydatabase = dict()

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

Then you can save your object mydatabase to a file.

But I'm not sure this is the right way to achieve what you want regarding synchronization between requests.

You can use memcached for something like this. However, you'll need to setup the memcached server.

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

Application is the right object to store (semi-)persistent data. However, as suggested on other anwser, you should consider using some kind of database to store this data.

However, you should take care that wen a session (or transaction) doesn't finish properly (eg you get a POST but no GET to trigger the action), you should delete the session data so as not to have your webserver leak memory.

From my experience, I'd suggest using Redis since it is easy to use and supports key expiration , a mechanism that comes handy when you need to manage session data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM