Flask-Restful 的请求前调用
我想用 Flask-RESTFUL 创建一个API,但有些东西我找不到。我不想在每次请求时都重复相同的操作,所以我想到了使用 before_request() 和 tear_down() 这两个方法。
1 个回答
0
你也可以为flask-restful的Resource
对象使用method_decorators
。
class Resource(MethodView):
"""
Represents an abstract RESTful resource. Concrete resources should
extend from this class and expose methods for each supported HTTP
method. If a resource is invoked with an unsupported HTTP method,
the API will return a response with status 405 Method Not Allowed.
Otherwise the appropriate method is called and passed all arguments
from the url rule used when adding the resource to an Api instance. See
:meth:`~flask_restful.Api.add_resource` for details.
"""
representations = None
method_decorators = []
如果你查看一下源代码,会发现它会按顺序应用这些装饰器:
for decorator in self.method_decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, ResponseBase): # There may be a better way to test
return resp
representations = self.representations or OrderedDict()