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