Tornado - Python global variable

懵懂的女人 提交于 2019-12-08 18:13:32

Your solution will have issues if you're handling more than one request at a time. Tornado is an async web framework so another request might overwrite your global var and set the user to someone else. It's good practice to store request depending data on self, tornado will make sure that data is altered by other simultaneous requests.

A solution that might work for you is to add your tool in the basic handler or create a decorator. It's tricky to sugest more details, please include more info in your question if you would like to get better alternatives.

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

Basically just subclass tornado.web.RequestHandlerand override the get_current_user method in your new/own BaseHandler.

Here the quote from the tornado docs:

tornado User authentication

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.

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.

You can see a fully working example in the official tornado blog demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!