In writing a tornado Http Server, I am having trouble with accessing an instance variable in my main class, which contains the tornado application object as well as start method, from a separate RequestHandler object. Consider the following crude 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's ref_object
pass
I need to access the ref_object instance of MyServer
in the post()
method of SomeHandler
and I need to make sure that the ref_object accessed in SomeHandler
is the same object if its changed in change_ref_object()
.
Somehandler is only referenced as a class when creating a python tornado web server (application), and it isn't clear how one would access such an instance of SomeHandler
to change its temporary ref_object when its changed in MyServer
.
It basically comes down to me not understanding where the instances of SomeHandler would exist within the scope of MyServer (or specifically, MyServer's application object).
When you create your Application
object, you can pass your ref_object
instance to SomeHandler
by placing it in a dict as a third argument to the tuple normally used to define the handler. So, in MyServer.__init__
:
self.application = tornado.web.Application([
(r"/test", SomeHandler, {"ref_object" : self.ref_object}),
])
Then add an 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()
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