Flask可插拔视图和登录需要 [英] Flask pluggable views and login required
本文介绍了Flask可插拔视图和登录需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
from flask.views import View
class ShowUsers(View):
def dispatch_request(self):
users = User.query.all()
return render_template('users.html',objects = users)
app.add_url_rule('/ users /',view_func = ShowUsers.as_view('show_users'))
那么我该如何强制在这个类/函数上使用login?
解决方案
有关装饰视图
使用Flask-Login?如果内置的 login_required
装饰器不适合基于分类的视图,那么你可以自己写 - 关键是调用 未经授权
关于 b
:
@wraps(f)
def decorator(* args,** kwargs):
if not current_user.is_authenticated():
return login_manager.unauthorized()
#或者如果你没有使用Flask-Login
#return redirect(url_for('login_page'))
return f(* args,** kwargs)
return decorator
I understand how a pluggable view works. What I currently do not understand is how to add a login required to a Class extending View. I currently do this:
from flask.views import View
class ShowUsers(View):
def dispatch_request(self):
users = User.query.all()
return render_template('users.html', objects=users)
app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))
So how do I force a loginrequired on this class/function?
解决方案
There's a section in the documentation about decorating views
Using Flask-Login? If the built in login_required
decorator isnt suitable for classed based views, then you can write your own - the key is the call to unauthorized
on the LoginManager
instance:
from functools import wraps
def user_required(f):
@wraps(f)
def decorator(*args, **kwargs):
if not current_user.is_authenticated():
return login_manager.unauthorized()
# or, if you're not using Flask-Login
# return redirect(url_for('login_page'))
return f(*args, **kwargs)
return decorator
这篇关于Flask可插拔视图和登录需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文