gpt4 book ai didi

python - 将两个 python 装饰器合二为一

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:53 24 4
gpt4 key购买 nike

这是我想组合的两个装饰器,因为它们非常相似,不同之处在于如何处理未经过身份验证的用户。我更希望有一个可以用参数调用的装饰器。

# 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():
...

我在 python 3.3 上使用 Bottle 框架。有可能做我想做的事吗?怎么办?

最佳答案

只需添加另一个包装器来捕获 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)并重命名了旧的 decoratorwrapper,通常的约定。

无论你在 @ 之后放置什么,它都是一个表达式,首先求值以找到实际的装饰器函数。 @helpers.requireAuthentication() 表示您要调用 requireAuthentication 并且它的返回值 然后用作函数的实际装饰器 @ 行适用于。

关于python - 将两个 python 装饰器合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com