1.管理员登录
步骤:
- app/__ init __.py中创建db对象
- app/models.py中导入db对象
- app/admin/forms.py中定义表单验证
- app/templates/admin/login.html中使用表单字段、信息验证、消息闪现
- app/admin/views.py中出来登录请求、保存会话
- app/admin/views.py定义登录装饰器、访问控制
实际操作:
1.app/admin/forms.py中定义登录表单验证
# 安装Flask-WTF模块
# app/admin/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
"""管理员登录表单"""
account = StringField(
label="账号", # 字段名称
# 账号不能为空
validators=[
DataRequired("请输入账号!")
],
# 描述
description="账号",
# 附加选项,前端页面上除了name和type,其它属性都要加上
render_kw={
"class": "form-control",
"placeholder": "请输入账号",
# "required": "required",
}
)
pwd = PasswordField(
label="密码",
validators=[
DataRequired("请输入密码!")
],
description="密码",
render_kw={
"class": "form-control",
"placeholder": "请输入密码",
# "required": "required",
}
)
submit = SubmitField(
'登录',
render_kw = {
"class": "btn btn-primary btn-block btn-flat",
}
)
2.替换html页面上的表单
# app/admin/views.py
@admin.route('/login')
def login():
login_form = LoginForm()
return render_template('admin/login.html', form=login_form)
# app/templates/admin/login.html
{{ form.account }} 替换 <input name="user" type="text" class="form-control" placeholder="请输入账号!">
{{ from.pwd }} 替换<input name="pwd" type="password" class="form-control" placeholder="请输入密码!">
{{ form.submit }} 替换<a id="btn-sub" type="submit" class="btn btn-primary btn-block btn-flat">登录</a>
在{{ form.submit }}下面加个{{ form.csrf_token }}
# app/__init__.py
<!--令牌 -->
<!-->>> import uuid-->
<!-->>> uuid.uuid4().hex-->
<!--'ec0eba98fb9d472b95ce240b7ee8f4e2'-->
app.config['SECRET_KEY'] = 'ec0eba98fb9d472b95ce240b7ee8f4e2'
3.页面错误信息显示
# app/admin/views.py
@admin.route('/login', methods=["GET", "POST"])
def login():
login_form = LoginForm()
# 提交时验证
if login_form .validate_on_submit():
# 获取表单数据
data = login_form .data
return render_template('admin/login.html', form=login_form)
<!-- 页面显示错误信息 -->
<!--app/templates/admin/login.html-->
{% for err in form.account.errors %}
<div class="col-md-12" id="input_user">
<font style="color:red">{{ err }}</font>
</div>
{% endfor %}
{% for err in form.pwd.errors %}
<div class="col-md-12" id="input_user">
<font style="color:red">{{ err }}</font>
</div>
{% endfor %}
<!-- form表单不需要action -->
4.校验账号和密码
# app/admin/forms.py
from app.models import Admin
from wtforms.validators import ValidationError
# validate_字段名称
def validate_account(self, field):
account = field.data
# 统计admin条数
admin = Admin.query.filter_by(name=account).count()
# 判断是否有条数
if admin == 0:
raise ValidationError("账号不存在")
# app/admin/models.py
# 检测密码
def check_password(self, pwd):
from werkzeug.security import check_password_hash
return check_password_hash(self.pwd, pwd)
5.前端页面上显示登录错误信息,flash闪出
<!--app/admin/views.py-->
from app.models import Admin
from flask import flash, session, request
@admin.route('/login', methods=["GET", "POST"])
def login():
login_form = LoginForm()
# 提交时验证
if login_form.validate_on_submit():
# 获取表单数据
data = form.data
admin = Admin.query.filter_by(name=data["account"]).first()
# 密码不正确
if not admin.check_pwd(data["pwd"]):
flash("密码错误!")
return redirect(url_for("admin.login"))
# 密码正确
session["admin"] = data["account"]
return redirect(request.args.get("next") or url_for("admin.index"))
return render_template('admin/login.html', form=login_form)
<!--app/templates/admin/login.html-->
{% for msg in get_flashed_messages() %}
<p class="login-box-msg" style="color:red;">{{ msg }}</p>
{% endfor %}
6.退出系统
<!--app/admin/views.py-->
@admin.route("/logout")
def logout():
session.pop("account", None)
return redirect(url_for("admin.login")
7.装饰器限制访问
<!--app/admin/views.py-->
from functools import wraps
def admin_login_req(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not session['admin'] is None:
return redirect(url_for("admin.login", next=request.url))
return f(*args, **kwargs)
return decorated_function
# 装饰器写完之后,在后台的每个函数都要加上这个装饰器
8.依然能登录,解决bug
<!--app/admin/views.py-->
from funtools import wraps
def admin_login_req(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if "admin" not in session:
return redirect(url_for("admin.login", next=request.url))
return f(*args, **kwargs)
return decorated_function
这样管理员的登录就完成了
网友评论