Share variable between HTTPServer / Application and Handlers

1,668 views
Skip to first unread message

ThinkChaos

unread,
Aug 27, 2013, 9:27:01 AM8/27/13
to python-...@googlegroups.com
I need to share a file descriptor between my application and the handlers (they need to write data to it).
I'm new to Tornado, so I don't think I can figure this out on my own.

My idea was to pass a handler instance instead of the class when initializing the app, allowing me to set the variable before.
But I don't think this is possible.

Is there a way for me to do this?

Lorenzo Bolla

unread,
Aug 27, 2013, 9:36:57 AM8/27/13
to python-...@googlegroups.com
Usually, I set attributes in the Application object, and then I access
them from the handlers as: Handler.application.my_attribute

HTH,
L.
> --
> You received this message because you are subscribed to the Google Groups
> "Tornado Web Server" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to python-tornad...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

ThinkChaos

unread,
Aug 27, 2013, 3:23:57 PM8/27/13
to python-...@googlegroups.com
I wasn't aware of the application attribute. That was exactly what I needed!
Thank you so much!

Ben Darnell

unread,
Aug 27, 2013, 8:14:15 PM8/27/13
to Tornado Mailing List
There are three basic strategies for this:

* Just use a global variable (or class attribute).  This has well-known drawbacks, but if you can live with them it's very easy to do.
* Attach it to the Application object.  You can either use an extra attribute on the Application object itself as Lorenzo suggested, or add it to the settings dictionary by passing extra keyword arguments to the Application constructor.  This is a little cleaner than the global variable option, especially if you create a separate Application object for each test.
* Store it in the URLSpec.  This would let each handler (or even different instances of the same handler) have their own values for this variable.  To do this, define an initialize method in your handler:
  def initialize(self, foo):
    self.foo = foo

and then pass a dictionary when configuring your urls:
  ('/somewhere', MyHandler, dict(foo=my_foo))

-Ben


--

ThinkChaos

unread,
Aug 28, 2013, 9:26:21 AM8/28/13
to python-...@googlegroups.com, b...@bendarnell.com
The URLSpec thing seems nice!
I went with the application attribute as Lorenzo suggested because I need the variable to be in sync between handlers.
Thanks for the suggestions, I'm sure someone will find them useful.
Reply all
Reply to author
Forward
0 new messages