Tornado Get Instance Variable Reference in RequestHandler

When writing Http Server Tornado, I am having problems accessing an instance variable in my main class, which contains the tornado application object, as well as the start method from a separate RequestHandler object. Consider the following example:

class MyServer(object): def __init__(self): self.ref_object = 0 self.application = #Add tornado.web.applicaiton here def change_ref_object(self, ref_obj): self.ref_object = ref_obj def start(self): #start the server pass class SomeHandler(tornado.web.RequestHandler): def post(self): #Yada, yada, yada #Call method on Myserver ref_object pass 

I need to access the ref_object MyServer MyServer in the MyServer post() SomeHandler , and I need to make sure that the ref_object accessed by SomeHandler is the same object if I change it in change_ref_object() .

The incorrect handler is only mentioned as a class when creating the python tornado web server (application), and it is unclear how you can access this SomeHandler instance to change its temporary ref_object when it changed in MyServer .

Mostly it comes to my mind not to understand where SomeHandler instances will exist within MyServer (or, in particular, the MyServer application object).

+7
python tornado
source share
1 answer

When you create your Application object, you can pass an instance of ref_object to SomeHandler by placing it in the dict as the third argument in the tuple commonly used to define a handler. So, in MyServer.__init__ :

 self.application = tornado.web.Application([ (r"/test", SomeHandler, {"ref_object" : self.ref_object}), ]) 

Then add the initialize method to SomeHandler :

 class SomeHandler(tornado.web.RequestHandler): def initialize(self, ref_object): self.ref_object = ref_object def post(self): self.ref_object.method() 
+15
source share

All Articles