如何在 Python 脚本上动态 enable/disable Tornado Auth?
How to dynamically enable/disable Tornado Auth on Python script?
我想要一个启动 Tornado 的 Python 脚本。我想只在生产阶段启用授权,在开发阶段禁用授权。
# This is the main page handler
class MainPageHandler(BaseHandler):
def get(self):
if not self.get_current_token():
self.redirect(self.reverse_full_url("tokenLogin"))
return
self.render('index.html')
# This is the main tornado app
class Application(tornado.web.Application):
def __init__(self, disableAuth=False):
...
# This is running in main function
Application(disableAuth).listen(PORT, HOST)
我可以使用 python 参数切换 on/off 身份验证吗?一个例子会非常非常好。
提前致谢
Application
对象作为 RequestHandler
对象的属性可用,因此只要您在 Application.__init__
中设置 self.disableAuth
属性,您就可以做一些事情在你的处理程序中像这样:
def get(self):
if not self.application.disableAuth:
# auth goes here...
如果您正在使用内置的用户身份验证支持并需要用户对象进行下游操作,您可以将授权检查添加到 get_current_user
,如下所示:
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
if self.application.settings.disableAuth:
return self.get_debug_user() # A method that returns a debug user.
else:
return self.get_authenticated_user() # Performs your actual authentication and returns the real user object.
class MainPageHandler(BaseHandler):
def get(self):
if not self.current_user:
self.redirect(self.reverse_full_url("tokenLogin"))
return
self.render('index.html')
目前我会使用一个全局标志(配置文件中的一个标志)来处理传递变量。
我想要一个启动 Tornado 的 Python 脚本。我想只在生产阶段启用授权,在开发阶段禁用授权。
# This is the main page handler
class MainPageHandler(BaseHandler):
def get(self):
if not self.get_current_token():
self.redirect(self.reverse_full_url("tokenLogin"))
return
self.render('index.html')
# This is the main tornado app
class Application(tornado.web.Application):
def __init__(self, disableAuth=False):
...
# This is running in main function
Application(disableAuth).listen(PORT, HOST)
我可以使用 python 参数切换 on/off 身份验证吗?一个例子会非常非常好。
提前致谢
Application
对象作为 RequestHandler
对象的属性可用,因此只要您在 Application.__init__
中设置 self.disableAuth
属性,您就可以做一些事情在你的处理程序中像这样:
def get(self):
if not self.application.disableAuth:
# auth goes here...
如果您正在使用内置的用户身份验证支持并需要用户对象进行下游操作,您可以将授权检查添加到 get_current_user
,如下所示:
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
if self.application.settings.disableAuth:
return self.get_debug_user() # A method that returns a debug user.
else:
return self.get_authenticated_user() # Performs your actual authentication and returns the real user object.
class MainPageHandler(BaseHandler):
def get(self):
if not self.current_user:
self.redirect(self.reverse_full_url("tokenLogin"))
return
self.render('index.html')
目前我会使用一个全局标志(配置文件中的一个标志)来处理传递变量。