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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With