Reputation: 20621
I am building a web server using Tornado 4.5.1 and Python 3.6. I want to initialize an object when starting the server and keep it available for the duration of the server run.
From this question: Does initialize in tornado.web.RequestHandler get called every time for a request? I understood that the initialize() functions inside RequestHandlers are called every time there is an HTTP request, and that to initialize once, I need to store this object inside the tornado.web.Application.
My question is: How I add this object to Application initialization? Do I need to subclass tornado.web.Application? Or is there API enabling this?
I couldn't understand this from the Tornado documentation.
Upvotes: 1
Views: 1261
Reputation: 24007
You can simply make it a module global:
my_global_var = set() # Or whatever type of object you need
Then the variable will be initialized when your program starts, and last for the program's lifetime. This is the simplest and clearest way to do one-time initialization in Python.
Upvotes: 2
Reputation: 591
You can subclass the Application
class and after that in your request handler you can access your application instance like this:
RequestHandler.application
or if you are in method from your request handler
self.application
Let's suppose that you have added a variable my_var
on your application, to access it you will do:
self.application.my_var
or
RequestHandler.application.my_var
Upvotes: 2