这是我想组合的两个装饰器,因为它们非常相似,区别在于如何处理未经身份验证的用户。我更喜欢有一个可以通过参数调用的装饰器。
# Authentication decorator for routes
# Will redirect to the login page if not authenticated
def requireAuthentication(fn):
def decorator(**kwargs):
# Is user logged on?
if "user" in request.session:
return fn(**kwargs)
# No, redirect to login page
else:
redirect('/login?url={0}{1}'.format(request.path, ("?" + request.query_string if request.query_string else '')))
return decorator
# Authentication decorator for routes
# Will return an error message (in JSON) if not authenticated
def requireAuthenticationJSON(fn):
def decorator(**kwargs):
# Is user logged on?
if "user" in request.session:
return fn(**kwargs)
# No, return error
else:
return {
"exception": "NotAuthorized",
"error" : "You are not authorized, please log on"
}
return decorator
目前我正在将这些装饰器用于特定路线,例如
@get('/day/')
@helpers.requireAuthentication
def day():
...
@get('/night/')
@helpers.requireAuthenticationJSON
def night():
...
我更喜欢这个:
@get('/day/')
@helpers.requireAuthentication()
def day():
...
@get('/night/')
@helpers.requireAuthentication(json = True)
def night():
...
我使用 Bottle 框架使用 python 3.3。可以做我想做的事吗?如何?
只需添加另一个包装器即可捕获json
范围:
def requireAuthentication(json=False):
def decorator(fn):
def wrapper(**kwargs):
# Is user logged on?
if "user" in request.session:
return fn(**kwargs)
# No, return error
if json:
return {
"exception": "NotAuthorized",
"error" : "You are not authorized, please log on"
}
redirect('/login?url={0}{1}'.format(request.path, ("?" + request.query_string if request.query_string else '')))
return wrapper
return decorator
我把你原来的名字改了requireAuthentication
功能为decorator
(因为这就是该函数的作用,它装饰了fn
)并重命名为旧的decorator
to wrapper
,通常的约定。
无论你放什么after the @
是一个表达式,首先评估以找到实际的装饰器函数。@helpers.requireAuthentication()
意味着你想打电话requireAuthentication
这是返回值然后用作函数的实际装饰器@
线适用于.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)