Login 示例
一旦用户通过验证,你可以使用 login_user
函数让用户登录。例如:
@app.route('/login', methods=['GET', 'POST'])
def login():
# Here we use a class of some kind to represent and validate our
# client-side form data. For example, WTForms is a library that will
# handle this for us, and we use a custom LoginForm to validate.
form = LoginForm()
if form.validate_on_submit():
# Login and validate the user.
# user should be an instance of your `User` class
login_user(user)
flask.flash('Logged in successfully.')
next = flask.request.args.get('next')
# next_is_valid should check if the user has valid
# permission to access the `next` url
if not next_is_valid(next):
return flask.abort(400)
return flask.redirect(next or flask.url_for('index'))
return flask.render_template('login.html', form=form)
警告: 你必须验证 next
参数的值。如果不验证的话,你的应用将会受到重定向的攻击。
就这么简单。你可用使用 current_user
代理来访问登录的用户,在每一个模板中都可以使用 current_user
:
{% if current_user.is_authenticated() %}
Hi {{ current_user.name }}!
{% endif %}
需要用户登入 的视图可以用 login_required
装饰器来装饰:
@app.route("/settings")
@login_required
def settings():
pass
当用户要登出时:
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(somewhere)
他们会被登出,且他们会话产生的任何 cookie 都会被清理干净。
当前内容版权归 wizardforcel 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 wizardforcel .