Search code examples
pythontornado

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.


Solution

  • 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.