Flask 验证登录问题,求助
class User(db.Model):global pwd
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), unique=True)
pwd = db.Column(db.String(510))
addtime = db.Column(db.DateTime, index=True, default=datetime.now)
userlogs = db.relationship("UserLog", backref="user")
def __repr__(self):
return "<User %r>" % self.name
def check_pwd(self, pwd):
return check_password_hash(self.pwd, pwd)
def login():
# global pwd
form = LoginForm()
if form.validate_on_submit():
data = form.data
user = User.query.filter_by(name = data["name"]).first()
if user.check_pwd(data['pwd']):
userlog = UserLog(
user_id=user.id,
ip=request.remote_addr
)
db.session.add(userlog)
db.session.commit()
session["name"] = user.name
return redirect(url_for("home.user"))
return render_template("home/login.html", form=form)
def check_password_hash(pwhash: str, password: str) -> bool:
"""Check a password against a given salted and hashed password value.
In order to support unsalted legacy passwords this method supports
plain text passwords, md5 and sha1 hashes (both salted and unsalted).
Returns `True` if the password matched, `False` otherwise.
:param pwhash: a hashed string like returned by
:func:`generate_password_hash`.
:param password: the plaintext password to compare against the hash.
"""
if pwhash.count("$") < 2:
return False
method, salt, hashval = pwhash.split("$", 2)
return hmac.compare_digest(_hash_internal(method, salt, password), hashval)
求教,问题出在哪里啊,现在我的demo注册功能正常,后台可以看到注册的数据,但是登陆功能不正常,任意输入数据,都直接跳转错误。程序里的错误信息如图 丢完整代码, kk159 发表于 2021-6-14 17:02
丢完整代码,
https://github.com/xiamids/python-flask-login-register{:1_893:} 本帖最后由 wanbinqs 于 2021-6-14 17:10 编辑
kk159 发表于 2021-6-14 17:02
丢完整代码, 这是最关键的两个文件,hash的 都用的库里的文件啊
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from werkzeug.security import check_password_hash
import pymysql, os
from flask import jsonify
app = Flask(__name__)
# 数据库配置
HOSTNAME = 'localhost'
PORT = '3306'
DATABASE = 'movic'
USERNAME = 'root'
PASSWORD = 'root'
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
app.config["SECRET_KEY"] = os.urandom(24)
db = SQLAlchemy(app)
# 会员
class User(db.Model):
global pwd
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), unique=True)
pwd = db.Column(db.String(510))
addtime = db.Column(db.DateTime, index=True, default=datetime.now)
userlogs = db.relationship("UserLog", backref="user")# 会员日志外键关联
def __repr__(self):
return "<User %r>" % self.name
def check_pwd(self, pwd):
return check_password_hash(self.pwd, pwd)
class UserLog(db.Model):
"""
会员登录日志表
"""
__tablename__ = "userlog"# 表名
id = db.Column(db.Integer, primary_key=True, autoincrement=True)# 编号
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))# 所属会员
ip = db.Column(db.String(100))# 登录IP
addtime = db.Column(db.DateTime, index=True, default=datetime.now)# 登录时间;
def __repr__(self):
return "<UserLog %r>" % self.id
if __name__ == '__main__':
db.drop_all()
db.create_all()
from . import home
from flask import render_template, redirect, url_for, flash, session, request
from app.home.forms import RegistForm, LoginForm
from app.models import User, db, UserLog
from datetime import datetime
from werkzeug.security import generate_password_hash
from functools import wraps
from werkzeug.security import check_password_hash
# 登录装饰器
def user_login_req(func):
@wraps(func)
def decorated_function(*args, **kwargs):
if "user" not in session:
return redirect(url_for("home.login"))
return func(*args, **kwargs)
return decorated_function
# 前端首页
@home.route("/")
def index():
return render_template("home/index.html")
# 用户中心
@home.route("/user")
@user_login_req
def user():
return render_template("home/user.html")
# 用户登录
@home.route("/login", methods=["GET", "POST"])
def login():
# global pwd
form = LoginForm()
if form.validate_on_submit():
data = form.data
user = User.query.filter_by(name = data["name"]).first()
if user.check_pwd(data['pwd']):
userlog = UserLog(
user_id=user.id,
ip=request.remote_addr
)
db.session.add(userlog)
db.session.commit()
session["name"] = user.name
return redirect(url_for("home.user"))
return render_template("home/login.html", form=form)
# 退出登录
@home.route("/logout",methods=["GET", "POST"])
def logout():
form = LoginForm()
if 'name' in session:
session.clear()
return redirect(url_for("home.login"))
return render_template("home/login.html", form=form)
# 会员注册
@home.route("/register", methods=["GET", "POST"])
def register():
form = RegistForm()
if form.validate_on_submit():
data = form.data
user = User(
name=data["name"],
pwd=generate_password_hash(data["pwd"]),
addtime=datetime.now()
)
db.session.add(user)
db.session.commit()
flash("注册成功", "ok")
return render_template("home/register.html", form=form)
wanbinqs 发表于 2021-6-14 17:08
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from da ...
git可以了 不用贴代码,稍等 我看看 kk159 发表于 2021-6-14 17:10
git可以了 不用贴代码,稍等 我看看
{:1_893:}感谢大佬,这几天搞这个都魔怔了,不知道问题在哪里 wanbinqs 发表于 2021-6-14 17:11
感谢大佬,这几天搞这个都魔怔了,不知道问题在哪里
晚点帮你看,代{过}{滤}理有点问题 ,我要爬几个回来先,不然GitHub太慢了,,你留意pull 就ok! kk159 发表于 2021-6-14 17:18
晚点帮你看,代{过}{滤}理有点问题 ,我要爬几个回来先,不然GitHub太慢了,,你留意pull 就ok!
好的 感谢:handshake:handshake def login():
form = LoginForm()
if form.validate_on_submit():
data = form.data
user = User.query.filter_by(name=data["name"]).first()
if user is not None and user.check_pwd(data["pwd"]):
def user_login_req(func):
@wraps(func)
def decorated_function(*args, **kwargs):
if session.get('name'):
return func(*args, **kwargs)
return redirect(url_for("home.login"))
登录的时候要先判断是否能取到用户,登录装饰器要判断登录时 往session中放的东西 1.你的安装依赖,你将系统的库都打包进去了吧?根据你的安装依赖导入根本跑不起
2.我根据你home、view里导了pymysql。flask 还有flask_sqlalchemy, 跑manage。还有要个wtf 基本跑起来。
3.不明白你用这个微电影的干嘛?反正注册我都报错了。应该是类库的问题,你先处理好这个问题,不然我无法复现你的错误。。你可以自己重新clone下 在安装库,测试能跑?
4.你的flask布局有点问题,参考我这个初始的https://github.com/leemamas/init_flask,model里面方db。。。。。。
5.从你第一个贴图报错来看,错误应该user没获取到,所以没user这个实例,自然报错提示没绑定check_pwd的方法!