简体   繁体   English

Tornado与Web.py的ctx模块相对应的是什么?

[英]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. 我想学习如何在龙卷风中使用web.py的ctx模块之类的东西。

Thanks! 谢谢!


Edit: I am trying to save user's credentials in a global context like with the ctx module. 编辑:我正在尝试在全局上下文中(如ctx模块)保存用户的凭据。 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? 我想知道实现此目标的正确方法是什么?

You can get most of the information contained in ctx from the RequestHandler.request object, which is a tornado.httpserver.HTTPRequest instance. 您可以从RequestHandler.request对象(它是tornado.httpserver.HTTPRequest实例)中获取ctx包含的大多数信息。

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. ctx中包含的一些内容可能需要从self.request.headers撤出,但我认为一切都已存在。

Tornado doesn't provide anything equivalent to the session data ctx provides. 龙卷风没有提供与ctx提供的会话数据等效的任何东西。 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. 一种是称为tornado.web.authenticated的装饰器,您可以使用它来装饰希望验证用户身份的任何方法。 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). 您还应该实现get_current_userget_login_url ,这是经过authenticated装饰器用来确定用户是否已通过身份验证;如果没有登录, get_login_url应该返回用户应该重定向到的网址(通常这应该是您的登录页面) )。 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. 用户登录后,可以使用set_secure_cookie将其会话存储在安全的cookie中,然后在get_current_user调用get_secure_cookie以稍后验证会话。

See this question for more general information on handling sessions with Tornado: standard way to handle user session in tornado 有关使用Tornado处理会话的更多常规信息,请参阅此问题:在Tornado 中处理用户会话的标准方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM