尝试使用 hashlib 和 Flask 散列用户名并将其存储在数据库中

问题描述

我正在尝试使用 hashlib 对用户名进行哈希处理,该用户名是在将表单提交到数据库之前从表单中获取的。

代码

draw

我能够获取用户名并提交而无需对其进行哈希处理。但是,一旦我使用这一行:

sircle()

它给了我错误错误绑定参数 2 - 可能不受支持的类型。散列和存储值应该相对容易,所以我真的不确定我哪里出错了。我也遵循了有关 hashlib 的文档。

任何帮助将不胜感激。


编辑:在玩了一会儿之后,我设法想出了一个不同的错误。我将散列代码更改为如下所示:

@auth.route('/sign-up',methods=['GET','POST']) #enabling POST request method on this page
def signup(): #create function to handle route
    if request.method == 'POST': #if POSTING to server get data from form
        username = request.form.get('username')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')
        email = request.form.get('email')
        
        #checks database for already existing account name and email
        account = Account.query.filter_by(username=username).first()
        if account:
            flash('User already exists',category='error')
        emailCheck = Account.query.filter_by(email=email).first()
        if emailCheck:
            flash('User already exists',category='error')

        #perform some data checks
        if len(email) < 4:
            flash('Email is too short',category='error')
        elif password1 != password2:
            flash('Passwords do not match',category='error')
        elif len(username) < 5:
            flash('Username too short',category='error')
        else:
            #hash the username
            username = hashlib.sha256(username.encode('utf-8'))
            #create new user using User schema
            new_account = Account(email=email,username=username,password=generate_password_hash(password1,method='sha256')) #user name and password are created and hashed before being stored.
            db.session.add(new_account)
            db.session.commit()
            login_user(new_account,remember=True)
            flash('Account Created',category='success')
            return redirect(url_for('views.getuserinfo'))

    return render_template("signup.html",user=current_user)

追溯:

username = hashlib.sha256(username.encode('utf-8'))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)