Gre*_*reg 6 python permissions authorization cherrypy decorator
我有一个讨厌的应用程序和一些我想开始的视图,只允许某些用户查看它们,并将其他人发送到授权所需页面.
有没有办法我可以用自定义装饰器做到这一点?我认为这将是最优雅的选择.
这是我想要做的基本示例:
class MyApp:
@authorization_required
def view_page1(self,appID):
... do some stuff ...
return html
def authorization_required(func):
#what do I put here?
Run Code Online (Sandbox Code Playgroud)
在作为装饰器调用时,authorization_required函数也可以接受allow_group1,allow_group2等参数吗?或者我是否需要为每个组分别设置一个装饰器?
fum*_*chu 14
你真的不想为CherryPy编写自定义装饰器.相反,您想要编写一个新工具:
def myauth(allowed_groups=None, debug=False):
# Do your auth here...
authlib.auth(...)
cherrypy.tools.myauth = cherrypy.Tool("on_start_resource", myauth)
Run Code Online (Sandbox Code Playgroud)
有关更多讨论,请参见http://docs.cherrypy.org/en/latest/extend.html#tools.这比编写自定义装饰器有几个好处:
@cherrypy.tools.myauth(allowed_groups=['me'])
它已经知道如何在同一个函数上破解cherrypy.exposed._cp_config
)或每个URI树(在配置文件或dicts中)应用工具.您甚至可以混合它们并通过装饰器提供基本功能,然后覆盖它们在配置文件中的行为.好的,在这种情况下,你的装饰器看起来像这样:
# without any parameters
def authentication_required(f):
@functools.wraps(f)
def _authentication_required(*args, **kwargs):
# Do you login stuff here
return f(*args, **kwargs)
return _authentication_required
# With parameters
def authentication_required(*allowed_groups):
def _authentication_required(f):
@functools.wraps(f)
def __authentication_required(*args, **kwargs):
# Do you login stuff here
return f(*args, **kwargs)
return __authentication_required
return _authentication_required
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3285 次 |
最近记录: |