登录页面
完成登录功能
添加post方法 (apps/cms/views.py)
完成form表单验证 (apps/cms/forms.py)
后台用户的注册
通过命令行添加
用户名 ellen 密码admin 邮箱ellen@qq.com
cmder:添加 用户名 密码 邮箱
python manage.py create_cms_user -u ellen -p 111111 -e el@qq.com
登录业务逻辑
apps/cms/views.py
# @ Time : 2020/5/13
# @ Author : Ellen
from flask import Blueprint, render_template, views, request, redirect, url_for, session
from apps.cms.forms import LoginForm
from apps.cms.models import CMSUser
cms_bp = Blueprint("cms", __name__, url_prefix='/cms')
# from .hooks import before_request
# 通过构子函数 解决问题(未成功登录也能直接进入cms index主页)
@cms_bp.before_request
def before_request():
# if not request
print(request.path)
if not request.path.endswith(url_for('cms.login')):
user_id = session.get('user_id')
if not user_id:
return redirect(url_for('cms.login'))
@cms_bp.route("/")
def index():
# print(session.get('user_id'))
return "cms index"
@cms_bp.route("/text/")
def demo():
return "测试是否可以访问"
class LoginView(views.MethodView):
def get(self, message=None):
return render_template('cms/cms_login.html', message=message)
def post(self):
login_form = LoginForm(request.form)
if login_form.validate():
# 数据库验证 接收表单发送的方式
email = login_form.email.data
password = login_form.password.data
remember = login_form.remember.data
user = CMSUser.query.filter_by(email=email).first()
if user and user.check_password(password):
session['user_id'] = user.id
if remember:
session.permanent = True
# 登录成功 跳转首页
return redirect(url_for('cms.index'))
else:
return self.get(message="邮箱或者密码错误")
else:
# print(login_form.errors.popitem()[1][0])
# return "表单验证错误"
message = login_form.errors.popitem()[1][0]
return self.get(message=message)
cms_bp.add_url_rule("/login/", view_func=LoginView.as_view('login'))
templates/cms/cms_login.html
错误信息显示:
cms/models.py - 加密验证方法
# @ Time : 2020/5/13
# @ Author : Ellen
from exts import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
class CMSUser(db.Model):
__tablename__ = "cms_user"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(50), nullable=False)
_password = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(50), nullable=False, unique=True)
join_time = db.Column(db.DateTime, default=datetime.now)
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
@property
def password(self):
return self._password
@password.setter
def password(self, raw_password):
self._password = generate_password_hash(raw_password)
def check_password(self, raw_password):
result = check_password_hash(self.password, raw_password)
return result
config.py
session 配置 SECRET_KEY
# @ Time : 2020/5/13
# @ Author : Ellen
import os
HOSTNAME = '127.0.0.1'
DATABASE = 'bbs'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset?'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URL
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(15)
CSRFProtect保护
# @ Time : 2020/5/12 1:24
# @ Author : Ellen
from flask import Flask
from exts import db
from apps.cms.views import cms_bp
from apps.front.views import front_bp
import config
from flask_wtf import CSRFProtect
# 前台 front
# 后台 cms 用户模型
# 公共的 common
app = Flask(__name__)
# CSRFProtect 保护
CSRFProtect(app)
app.config.from_object(config)
db.init_app(app)
app.register_blueprint(cms_bp)
app.register_blueprint(front_bp)
if __name__ == '__main__':
app.run(debug=True)
decorators.py
装饰器验证是否登录 也可用构子函数
# @ Time : 2020/5/13
# @ Author : Ellen
# 装饰器验证是否登录
from flask import session, redirect, url_for
def login_required(func):
def inner(*args, **kwargs):
if "user_id" in session:
return func(*args, **kwargs)
else:
return redirect(url_for('cms.login'))
return inner
可将构子函数单独写在hooks.py中
# @ Time : 2020/5/13 4:22
# @ Author : Ellen
from flask import request, url_for, redirect, session
from.views import cms_bp
from .models import CMSUser
# 通过构子函数 解决问题(未成功登录也能直接进入cms index主页)
@cms_bp.before_request
def before_request():
# if not request
print(request.path)
if not request.path.endswith(url_for('cms.login')):
user_id = session.get('user_id')
if not user_id:
return redirect(url_for('cms.login'))
# 完善登录页面-用户名渲染
if 'user_id' in session:
user_id = session.get('user_id')
user = CMSUser.query.get(user_id)
print(user)
if user:
g.cms_user = user
apps/cms/views.py
注销后返回登录页面
@cms_bp.route('/logout/')
def logout():
# 删除 session user_id
# 重定向 登录页面
del session['user_id']
return redirect(url_for('cms.login'))
tmplates/cms/cms_index.html
点击注销:返回首页