出于某种原因,当我查询数据库并将变量命名为 user_db 然后刷新变量 user_db.hashed_password 时,我没有得到任何结果。这是为什么?

问题描述 投票:0回答:1

抱歉,我没有包含 html 文件和每个导入。

我尝试创建最简单的示例。希望代码能够运行。
我故意缩短了登录功能。

当我查询数据库并命名变量

user_db
时,然后我尝试刷新变量
flash(user_db.username)
flash(user_db.username)
我得到用户名和电子邮件的输出。如果我去
flash(user_db.hashed_password)
输出就是
None

为什么输出

user_db.hashed_password
None

应用程序.py


from flask import Flask
app = Flask(__name__)


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    hashed_password = db.Column(db.String(128))
    email = db.Column(db.String(120), unique=True)
    
 
    from argon2 import PasswordHasher

    def hash_password(self, plaintext_password_form):
        ph = PasswordHasher()
        self.password_hashed_form  = ph.hash(plaintext_password_form)
        return self.password_hashed_form 
    


    
    def compare_hashed_passwords(self, hashed_password_db, plaintext_password_form):
        '''   
        The code runs in the /login route.
        You should query the db for hashed_password 
        or the value will be a different hash; 
        and the function ph.verify will return False even 
        if the password form match with the hash password.
        '''
        
        ph = PasswordHasher()
        try:
            ph.verify(hashed_password_db, plaintext_password_form)
            signedin = True
        except:
            signedin = False
        return signedin
        # have to redirect 
    


@app.route("/home", methods = ['POST', 'GET'])
def home():
   render_template(home.html)







class RegistrationForm(FlaskForm):
    '''
    This is in /register route.
    The forms are username, email, password and confirm_password
    '''
    username = StringField('username')
    
    email = StringField('email')


    password = PasswordField('password')
 
    confirm_password = PasswordField('confirm_password')
    submit = SubmitField('Submit'),




   

@app.route("/register", methods = ['POST', 'GET'])
def register():

    # if the user is logged in make so they can't go to the register page. 
    if current_user.is_authenticated:
        return redirect(url_for(('auth.home')))
    
    form = RegistrationForm()
    # form.validate_on_submit(): are always the same line of render template to always allow a get request.
    if form.validate_on_submit():

        username_form = form.username.data
        email_form = form.email.data
        plaintext_password_form = form.password.data
        confirm_plaintext_password_form = form.confirm_password.data
        # Use the code, if you are adding code to the database the first time
        adding_user = User(username=username_form, email=email_form)
        # hash the password    
        hashed_password_form = adding_user.hash_password(plaintext_password_form)
        
     
        
        
        adding_user_hahed_password = User(hashed_password=hashed_password_form)
        db.session.add(adding_user, adding_user_hahed_password )
        db.session.commit()
               
       
        return redirect(url_for('auth.login'))
    return render_template('register.html',title='register', form=form)






def check_if_username_or_email_is_in_db(form, field):
    '''
    if the username or email is in the db the code works,
    if not it raises an ValidationError.
    The if statement checks if the query is empty/has no values in db.
    This runs in the LoginForm in auth/forms.py
    '''
  
 
    # if empty list [] return True 
    if not User.query.filter_by(username=field.data).first() or not User.query.filter_by(username=field.data).first(): 
        raise ValidationError('The username or email does not exist. Please retype your username or email.')   



# I included this validator because I am not sure if that could be causing the error. 
class LoginForm(FlaskForm):
    '''
    This is in /Login route.
    The forms are username, email, password and confirm_password
    '''
    
    username_or_email = StringField('username_or_email', validators=
    [
    check_if_username_or_email_is_in_db
    ])    
    
    password = PasswordField('password')
    submit = SubmitField('Submit')
  



@app.route("/login",methods = ['POST', 'GET'])
def login():
    # if the user is logged in make it so they can't go to the login page. 
    if current_user.is_authenticated:
        return redirect(url_for('auth.home')) 

    form = LoginForm()
    if form.validate_on_submit():

        # allows you to register with a username or email
        username_or_email_form = form.username_or_email.data
        plaintext_password_form = form.password.data
 

        username_db = User.query.filter_by(username=username_or_email_form).first()
        email_db = User.query.filter_by(email=username_or_email_form).first()
                
        if username_db.username == username_or_email_form:
            user_db = User.query.filter_by(username=username_or_email_form ).first()
            flash(user_db)

        elif email_db.email == username_or_email_form:
            user_db = User.query.filter_by(email=username_or_email_form).first()
        else:
            flash('username or email do not exist')
            flash(user_db)
        
               
        flash(user_db.hashed_password)
        
        hashed_password_db = user_db.hashed_password
        return render_template('home.html')

           

if __name__ == '__main__':
app.run(debug=True)
flask flask-sqlalchemy flask-wtforms
1个回答
0
投票

该错误是由 2 个

User()...
实例引起的。为了清楚起见,这 2 个实例是
adding_user = User(username=username_form, email=email_form)
adding_user_hahed_password = User(hashed_password=hashed_password_form)

然后在登录路径中,当我尝试访问1时

user_db = User.query.filter_by(...).first()
。我只使用 1 个
User
实例,因为如上所述,另一个实例被前一个
User
覆盖。希望我解释得很好。

© www.soinside.com 2019 - 2024. All rights reserved.