Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share data between requests in Tornado Web

Tags:

python

tornado

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.

like image 749
RevMoon Avatar asked Sep 02 '12 22:09

RevMoon


2 Answers

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.

like image 124
Konrad Reiche Avatar answered Sep 25 '22 01:09

Konrad Reiche


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.

like image 38
pintoch Avatar answered Sep 24 '22 01:09

pintoch