6-1 管理员登录
- 改写了models.py
- form表单验证,安装flask_wtf
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
class LoginForm(FlaskForm):
account = StringField(
label="账号",
validators=[
DataRequired("请输入账号!")
],
description="账号",
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",
}
)
- admin/views.py
@admin.route("/login/")
def login():
form = LoginForm()
return render_template("admin/login.html", form=form)
- templates/admin/login
账号:
<input name="user" type="text" class="form-control" placeholder="请输入账号!">
替换成
{{ form.account }}
密码:
<input name="pwd" type="password" class="form-control" placeholder="请输入密码!">
替换-
{{ form.pwd }}
登陆:
<a id="btn-sub" type="submit" class="btn btn-primary btn-block btn-flat">登录</a>
替换-
{{ form.submit }}
builtins.KeyError
- app/init.py
app.config["SECRET_KEY"] = '5b80d0d6ea6f43c6b3ed0a61f05436cd'
- templates/admin/login
{{ form.submit }}
{{ form.csrf_token }}
RUN-1:Form表单验证,显示错误信息
@admin.route("/login/", methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
data = form.data
return render_template("admin/login.html", form=form)
- login.html
{% for err in form.pwd.errors %}
<div class="col-md-12">
<font style="color:red"> {{ err }}</font>
</div>
{% endfor %}
- form注释掉前端验证类
class LoginForm(FlaskForm):
account = StringField(
label="账号",
validators=[
DataRequired("请输入账号!")
],
description="账号",
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",
}
)
RUN-2:验证表单提交
- form中验证用户名是否存在。
def validate_account(self, field):
account = field.data
admin = Admin.query.filter_by(name=account).count()
if admin == 0:
raise ValidationError("账号不存在!")
-
测试不存在的用户名
RUN-3 验证密码
- model中加入验证密码方法
class Admin(db.Model):
__tablename__ = "admin"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True)
pwd = db.Column(db.String(100))
is_super = db.Column(db.SmallInteger)
role_id = db.Column(db.Integer, db.ForeignKey('role.id'))
addtime = db.Column(db.DateTime, index=True, default=datetime.now)
adminlogs = db.relationship('Adminlog', backref='admin')
oplogs = db.relationship('Oplog', backref='admin')
def __repr__(self):
return "<Admin %r>" % self.name
def check_pwd(self, pwd):
from werkzeug.security import check_password_hash
return check_password_hash(self.pwd, pwd)
- forms
@admin.route("/login/", methods=["GET","POST"])
def login():
form = LoginForm()
if 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=form)
- 模板
{% for msg in get_flashed_messages() %}
<p class="login-box-msg">{{ msg }}</p>
{% endfor %}
运行结果:重定向,显示密码错误
RUN-4: 装饰器访问限制,没有登陆不能访问主页。
- views
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
@admin.route("/")
@admin_login_req
def index():
return render_template("admin/index.html")
- views
@admin.route("/logout/")
@admin_login_req
def logout():
session.pop("admin", None)
return redirect(url_for("admin.login"))
6-2标签管理
views-forms-templates