我目前有一个视图,根据用户是否匿名以及我使用的atm,返回不同的响应:
@app.route("/anonymous")
def anonymous_page():
if current_user.is_anonymous:
return render_template("anonymous_page.html")
return render_template("user_page.html")
我想制作一个decorator,我们称之为@show_only_to_anonymous
,它可以用一个返回语句在普通视图函数上使用,它将执行如下操作:
@app.route("/anonymous")
@show_only_to_anonymous
# if the user is anonymous, return the decorated function's view,
# elif the user is NOT anonymous, return "user_page.html"
def anonymous_page():
return render_template("anonymous_page.html")
我知道有一个login_required
装饰程序,我去看了一下源代码here,它在引擎盖下使用LocalProxy
作为current_user
,试图复制它,但失败了
我想我对flask框架的理解是缺乏的,因为我对它有点陌生,有人有想法吗
编辑:
通过查看flask login的源代码,我成功地实现了它,文件是:flask_login/utils.py
,我使用了相同的flask
和werkzeug.local
函数和其他对象,并在我的项目中创建了一个新文件,我将其命名为custom_decorators.py
,并作为模块导入我的routes.py
文件中,这些是custom_decorators.py
的内容:
from functools import wraps
from werkzeug.local import LocalProxy
from flask import _request_ctx_stack, has_request_context, current_app
current_user = LocalProxy(lambda: _get_user())
def _get_user():
if has_request_context() and not hasattr(_request_ctx_stack.top, 'user'):
current_app.login_manager._load_user()
return getattr(_request_ctx_stack.top, 'user', None)
def show_only_to_anonymous(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if not current_user.is_anonymous:
return current_app.view_functions['show_to_known_users'](*args, **kwargs)
return func(*args, **kwargs)
return decorated_view
现在,在我的routes.py
中,我可以这样做:
# this page can only be seen by anonymous users
@app.route("/anonymous")
@show_only_to_anonymous
def anonymous_page():
return render_template("anonymous_page.html")
# this will be called if a logged in user goes to mywebsite.com/anonymous:
@app.route("/show_to_known_users")
def show_to_known_users():
return redirect(url_for("user_page.html", code=301))
这个解决方案感觉有点“黑客”,有更好的方法吗
目前没有回答
相关问题 更多 >
编程相关推荐