官术网_书友最值得收藏!

Views

Flask implemented the views in a very flexible way, where you can define the routes along with them. Flask's generic views implementation is inspired by Django's generic views. We will look at a detailed description of method views in a further section, but here, we are going to use simple views.

The following is the views snippet.

File—auth/views.py:

from flask import render_template, redirect, url_for
from flask_login import login_user, login_required, logout_user

from app.auth import auth
from app.auth.forms import LoginForm, SignupForm
from app.auth.models import User

@auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user_by_email = User.query.filter_by(email=form.email.data).first()
if user_by_email is not None and user_by_email.verify_password(form.password.data):
login_user(user_by_email)
return redirect(url_for('todo.list'))
return render_template('auth/login.html', form=form)


@auth.route('/signup', methods=['GET', 'POST'])
def signup():
form = SignupForm()
if form.validate_on_submit():
if not User.query.filter_by(email=form.email.data).scalar():
User(
email = form.email.data,
password = form.password.data
).save()
return redirect(url_for('auth.login'))
else:
form.errors['email'] = 'User already exists.'
return render_template('auth/signup.html', form=form)
return render_template('auth/signup.html', form=form)


@auth.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('auth.login'))

Here, we created the /login, /signup, and /logout routes, which we invoke based on HTTP requests. We are rendering an empty form instance on the HTTP GET request and processing the data on the POST request by using the Flask-WTF method and the validate_on_submit() method. While rendering the template, we are passing the form instance and redirect based on required actions.

Let's have a look at the templates mechanism in the next section.

主站蜘蛛池模板: 吉隆县| 错那县| 水城县| 嘉兴市| 曲阜市| 屏山县| 两当县| 达尔| 隆安县| 台北县| 临洮县| 缙云县| 山丹县| 城口县| 蚌埠市| 富源县| 如皋市| 仲巴县| 凌源市| 富顺县| 高陵县| 利辛县| 永川市| 孝感市| 治县。| 皋兰县| 灵寿县| 长治县| 大悟县| 邛崃市| 钦州市| 革吉县| 宾川县| 南木林县| 喀什市| 阿拉善左旗| 思南县| 洪雅县| 昂仁县| 肇州县| 白城市|