龙卷风-Python全局变量 [英] Tornado - Python global variable

查看:67
本文介绍了龙卷风-Python全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将Tornado与SqlAlchemy一起使用,我需要在插入或更新操作中将当前用户从RequestHandler(tornado)传递给模型(SqlAlchemy).但是我不想直接将值传递给模型,例如:

I'm trying to use Tornado with SqlAlchemy, I need to pass the current user from RequestHandler (tornado) to models (SqlAlchemy) in the insert or update action. But I don't want to pass the value directly to the model, example:

#### RequestHandler POST method...
user = Session.query(User).get(1)
user.name = "bla, bla, bla..."
user.updated_by = self.current_user # don't use...
session.commit()

我在__init__.py文件中使用全局变量,并在RequestHandler中设置当前用户值,然后在SqlAlchemy的更新事件之前获取该值.

I'm using a global variable, in a __ init__.py file, and set the current user value in the RequestHandler and after, get the value, in before update event with SqlAlchemy.

这个想法是要知道哪个用户是创建者和更新者. 为什么我不希望像之前的示例那样直接将当前用户传递给模型?因为这将是其他开发人员的工具,而我试图让他们感到舒服,他们也可以忘记它,所以重要.

The idea is to know what user is the creator and updater. Why I don't want pass the current user directly to model like the before example ?, because this will be a tool for other developers, and I'm trying to make comfortable for them, also, they can forget about it and it is important.

这是个好主意,还是还有其他更好的方法?

Is this a good idea, or maybe is there other better way ?

推荐答案

每个处理程序(和模板)中都可以使用当前用户.如何确定,验证和设置当前用户取决于您.

The current user is available in every handler (and template). How you determine, authenticate and set the current user is up to you.

基本上只是子类,并在新的/拥有的BaseHandler中覆盖get_current_user方法.

这是龙卷风文档中的报价:

Here the quote from the tornado docs:

tornado用户身份验证

用户身份验证 当前身份验证的用户在每个请求处理程序中都可以用作self.current_user,在每个模板中都可以使用current_user.默认情况下,current_user为None.

User authentication The currently authenticated user is available in every request handler as self.current_user, and in every template as current_user. By default, current_user is None.

要在应用程序中实现用户身份验证,您需要在请求处理程序中覆盖get_current_user()方法,以根据Cookie的值确定当前用户.这是一个示例,使用户只需指定昵称即可登录应用程序,然后将其保存在cookie中.

To implement user authentication in your application, you need to override the get_current_user() method in your request handlers to determine the current user based on, e.g., the value of a cookie. Here is an example that lets users log into the application simply by specifying a nickname, which is then saved in a cookie.

您可以在官方龙卷风博客中看到完整的示例演示

这篇关于龙卷风-Python全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆