[英]Decorators with arguments with Flask
I'm trying to create a decorator with arguments and use it in conjunction with the flask module. 我正在尝试创建带有参数的装饰器,并将其与flask模块一起使用。
def ios_network_access(arg): #TODO:
def real_ios_network_access_decorator(fn):
def ios_network_access_inner():
if not request.json:
print("aborting because not json", fn.__name__)
abort(400)
try:
print("check args", arg)
return fn()
except Exception as e:
print("the following error occurred in:", fn.__name__)
print(request.json)
print(str(e))
print("---------------------------------")
abort(503)
return real_ios_network_access_decorator
@app.route("/someurl")
@ios_network_access("some argument")
def some_function_for_url():
pass
However, because flask uses function names in their decorator (flask requires uniqueness of function names and the decorator masks it), my end-points are not being created. 但是,由于flask在其装饰器中使用了函数名称(烧瓶需要函数名称的唯一性,并且装饰器将其屏蔽),因此未创建我的端点。
There is a very similar question here that asks regarding non-parameterized decorators; 关于非参数装饰器,这里有一个非常相似的问题。 however, due to the additional function layer, this question is different.
但是,由于增加了功能层,这个问题有所不同。 See AssertionError: View function mapping is overwriting an existing endpoint function: main
请参见AssertionError:视图函数映射正在覆盖现有的端点函数:main
Any thoughts on how to pass an argument into a decorator given flask's qwerks? 对于烧瓶的qwerks,如何将参数传递给装饰器有什么想法?
wraps
function is a convenience way to wrap your decorator function. wraps
函数是包装装饰器函数的便捷方法。 Attributes of the wrapper function are updated with the corresponding attributes from the original function. 包装函数的属性将使用原始函数中的相应属性进行更新。
from functools import wraps
def ios_network_access(arg):
def real_ios_network_access_decorator(fn):
@wraps(fn)
def ios_network_access_inner(*args, **kwds):
if not request.json:
print("aborting because not json", fn.__name__)
abort(400)
try:
print("check args", arg)
return fn(*args, **kwds)
except Exception as e:
print("the following error occurred in:", fn.__name__)
print(request.json)
print(str(e))
print("---------------------------------")
abort(503)
return ios_network_access_inner
return real_ios_network_access_decorator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.