mik*_*ong 5 python flask flask-restplus flask-restx
我有一个使用flask-restx和的 Flask 应用程序flask-login。我希望默认情况下所有路由都需要登录,并明确定义不需要身份验证的公共路由。我已经按照这个问题中给出的例子开始使用装饰器:
使 Flask-Login 的 login_required 成为默认值的最佳方法
它适用于函数端点,但不适用于restx资源端点。
我尝试将函数添加为装饰器,并使用该method_decorators字段。例如:
def public_route(decorated_function):
"""
This is a decorator to specify public endpoints in our flask routes
:param decorated_function:
:return:
"""
decorated_function.is_public = True
return decorated_function
class HelloWorld(ConfigurableResource):
method_decorators = {"get": [public_route]}
@public_route
@api.doc('Welcome message')
def get(self):
return {'hello': 'world'}
Run Code Online (Sandbox Code Playgroud)
这个测试通过了:
def test_hello_world_is_public():
api = Namespace('health', description='Health related operations')
hello = HelloWorld(api, config=None, logger=None)
is_public_endpoint = getattr(hello.get, 'is_public', False)
assert is_public_endpoint
Run Code Online (Sandbox Code Playgroud)
我的挑战是我看不到如何在我的身份验证逻辑中访问这个属性:
@app.before_request
def check_route_access():
"""
This function decides whethere access should be granted to an endpoint.
This function runs before all requests.
:return:
"""
is_public_endpoint = getattr(app.view_functions[request.endpoint], 'is_public', False)
if person_authorized_for_path(current_user, request.path, is_public_endpoint):
return
# Otherwise access not granted
return redirect(url_for("auth.index"))
Run Code Online (Sandbox Code Playgroud)
这适用于普通函数端点,但不适用于 restx 资源。
我知道这restx是将我的资源类包装在一个函数中,以便烧瓶可以进行调度,但我不知道如何从这里访问装饰器。所以我有一些问题:
| 归档时间: |
|
| 查看次数: |
1619 次 |
| 最近记录: |