微电影之用户的登陆功能实现
一、登陆表单
#导入加密密码模块 from werkzeug.security import generate_password_hash class LoginForm(FlaskForm): name=StringField( label="账号", validators=[ DataRequired("请输入账号!") ], description="账号", render_kw={ "placeholder":"请输入账号!" }) pwd = PasswordField( label="密码", validators=[ DataRequired("请输入用户密码!") ], description="管理员密码", render_kw={ "placeholder": "请输入用户密码!" } ) submit = SubmitField( '登陆', render_kw={ "class": "btn btn-lg btn-primary btn-block", }) #验证账号是否存在 def validate_name(self, field): name = field.data user = User.query.filter_by(name=name).count() if user == 0: raise ValidationError("账号不存在")
二、数据模型
class User(db.Model): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True) pwd = db.Column(db.String(100)) email = db.Column(db.String(32), unique=True) phone = db.Column(db.String(11), unique=True) info = db.Column(db.Text) face = db.Column(db.String(255), unique=True) addtime = db.Column(db.DateTime, index=True, default=datetime.now) uuid = db.Column(db.String(255), unique=True) userlogs = db.relationship('Userlog', backref='user') # 会员日志外键关系 comments = db.relationship('Comment', backref='user') # 评论外键关系 moviecols = db.relationship('Moviecol', backref='user') # 收藏外键关系 def __repr__(self): return "<User %r>" % self.name #验证密码函数 def check_pwd(self,pwd): from werkzeug.security import check_password_hash return check_password_hash(self.pwd,pwd)
三、views视图函数
@home.route("/login/",methods=["GET","POST"]) def login(): form = LoginForm() if form.validate_on_submit(): data = form.data user = User.query.filter_by(name=data["name"]).first() #验证密码 if not user.check_pwd(data["pwd"]): return redirect(url_for('home.login')) #添加到session中 session["user"] = data["name"] session['user_id'] = user.id #写入登录日志 userlog=Userlog( user_id=user.id, ip=request.remote_addr ) db.session.add(userlog) db.session.commit() return redirect(request.args.get("next") or url_for("home.user")) return render_template("home/login.html",form=form)
其他小知识:
用户密码的加密和验证
#加密 pwd="123456" pwd=generate_password_hash(pwd) #密码验证,密码正确返回True from werkzeug.security import generate_password_hash from werkzeug.security import check_password_hash pwd=generate_password_hash("123456") print(pwd) print(check_password_hash(pwd,"123456")) #结果如下 pbkdf2:sha256:50000$WwOZj97q$c3aaa3d4c733d2044bf5d79020d1483ee7eb6208114052249b82fc69fe8f4c7a True