Hypnos
Hypnos

Reputation: 285

What is Tornado's counterpart of Web.py's ctx module?

I would like to learn how to use something like web.py's ctx module in tornado.

Thanks!


Edit: I am trying to save user's credentials in a global context like with the ctx module. I know that such information can be passed with each request, but in that case I will need to pass this information to handlers each time? I wonder what is the correct way of accomplishing this?

Upvotes: 0

Views: 102

Answers (1)

dano
dano

Reputation: 94901

You can get most of the information contained in ctx from the RequestHandler.request object, which is a tornado.httpserver.HTTPRequest instance.

class MyHandler(tornado.web.RequestHandler):
    def get(self):
         # This is just some of the attributes available.
         print("host is {0.host}, ip is {0.ip}, HTTP method"
               " is {0.method}, protocol is {0.protocol}".format(self.request))

A few of the things that are contained in ctx you may have to pull out of self.request.headers, but I think it's all there.

Tornado doesn't provide anything equivalent to the session data ctx provides. Tornado is designed to be stateless, so this is purposely not implemented.

Note that tornado does provide some useful methods for dealing with authentication. One is a decorator called tornado.web.authenticated, which you can use to decorate any method you want the user to be authenticated to access. You should also implement get_current_user, which is what the authenticated decorator uses to determine if the user is authenticated, and get_login_url, which should return the url the user should be redirected to if they're not logged in (usually this should be your login page). When a user logs in, you can use set_secure_cookie to store their session in a secure cookie, and then call get_secure_cookie inside get_current_user to validate the session later.

See this question for more general information on handling sessions with Tornado: standard way to handle user session in tornado

Upvotes: 1

Related Questions