一、注册
- 安装flask_login
pip install flask_login
- 配置应用程序LoginManager
login_manager = LoginManager()
- 在manager.py中绑定
login_manager.init_app(app)
- 没有注册跳转地址
login_manager.login_view = "user.login"
在models.py文件中建立User表,继承 flask_login中的UserMixin
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(10), unique=True, nullable=False)
password = db.Column(db.String(130), unique=True, nullable=False)
icons = db.Column(db.String(150), nullable=True)
__tablename__ = 'user'
在注册验证时运用表单验证
- 安装flask_wtf
pip install flask_wtf
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, EqualTo, ValidationError
from user.models import User
from flask import url_for, redirect
class UserRegisterForm(FlaskForm):
# 定义用户名和密码是必填项
username = StringField('账号', validators=[DataRequired()])
password = PasswordField('密码', validators=[DataRequired()])
password2 = PasswordField('确认密码', validators=[DataRequired(), EqualTo('password', '密码不一致')])
submit = SubmitField('提交')
def validate_username(self, field):
user = User.query.filter(User.username == field.data).first()
if user:
return redirect(url_for('user.login'))
if len(field.data) < 3:
raise ValidationError('注册用户名不能少于3个字符')
if len(field.data) > 20:
raise ValidationError('注册用户名不能多于20个字符')
def validate_password(self, field):
if len(field.data) < 6:
raise ValidationError('密码不能少于6个字符')
if len(field.data) > 15:
raise ValidationError('密码不能大于15个字符')
def validate_password2(self, field):
if len(field.data) < 6:
raise ValidationError('密码不能少于6个字符')
if len(field.data) > 15:
raise ValidationError('密码不能大于15个字符')
在views.py文件中
@blue.route('/register/', methods=['GET', 'POST'])
def register():
# 表单对象
form = UserRegisterForm()
if request.method == 'GET':
return render_template('register.html', form=form)
if request.method == 'POST':
# 验证提交字段信息
if form.validate_on_submit():
username = form.username.data
password = form.password.data
# 实现注册,保存信息到User模型中
user = User()
user.username = username
user.password = generate_password_hash(password)
db.session.add(user)
db.session.commit()
return redirect(url_for('user.login'))
else:
return render_template('register.html', form=form)
- 配置才能跳转
@login_manager.user_loader
def loader_user(user_id):
return User.query.get(user_id)
二、登录
不使用表单验证,直接获取
- 运用flask_login自带的进行登录
login_user()
用generate_password_hash, check_password_hash进行加密解密
@blue.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login2.html')
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
# 检验是否为空
if not all([username, password]):
return render_template('login2.html')
user = User.query.filter(User.username == username).first()
if user:
# 获取到用户,进行密码判断
if check_password_hash(user.password, password):
# 密码正确 实现登录
# django中auth.login(request,user)
login_user(user)
return redirect(url_for('user.index'))
else:
error = '密码错误'
return render_template('login2.html', error=error)
else:
# 获取不到用户
error = '该用户没有注册,请去注册'
return render_template('login2.html', error=error)
三、注销
@blue.route('/logout/')
@login_required
def logout():
logout_user()
return redirect(url_for('user.login'))
- 装饰器直接调用
@login_required