【发布时间】:2018-05-02 12:06:18
【问题描述】:
当我使用名称和明文密码对用户登录进行基本身份验证时,用户已正确登录。
在注册过程中密码正确散列。 当我存储散列密码并尝试对其进行身份验证时,程序给出错误:
AttributeError: type object 'User' has no attribute 'query'
你能告诉我,有什么问题吗?我怀疑检查功能无法从 SQLAlchemy 数据库中找到散列密码。谢谢。
当我使用时:
query = s.query(User).filter(User.username.in_([POST_USERNAME]))
我明白了:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with User.password has an attribute 'split'
engine = create_engine('sqlite:///tutorial.db', echo=True)
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = 'XXXXX'
def hash_password(password):
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String(64))
password = Column(String(120))
email = Column(String(64))
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
Base.metadata.create_all(engine)
@app.route("/")
def index():
return render_template('index.html')
@app.route('/login', methods=['POST'])
def do_admin_login():
POST_USERNAME = str(request.form['username'])
POST_PASSWORD = str(request.form['password'])
Session = sessionmaker(bind=engine)
s = Session()
user = User.query.filter_by(username=POST_USERNAME).first()
if check_password(User.password, POST_PASSWORD) == True:
session['logged_in'] = True
else:
flash('wrong password!')
return index()
【问题讨论】:
标签: python python-3.x flask sqlalchemy