TypeError: no salt specified in flask(about sha256)

TypeError: no salt specified in flask(about sha256)

我正在按照 Youtube 中关于 flask 的教程来构建我自己的网站。但是,尽管我按照视频中的步骤进行了操作,但还是出现了错误。

我的操作系统是 MacOS,但视频作者使用 Linux

这是我的相关代码:

from passlib.hash import sha256_crypt

class register_form(Form):
    username=StringField('Username',[validators.Length(min=2,max=30)])
    password=PasswordField('Password',[
        validators.Length(min=4,max=20),
        validators.EqualTo('confirm',message='Password do not match')
        ])
    confirm=PasswordField('Confirm Password')
    email=StringField('E-mail',[validators.Length(min=6,max=30)])

@app.route('/register',methods=['GET','POST'])
def register():
    form_reg=register_form(request.form)
    if request.method=='POST' and form_reg.validate():
        username=form_reg.username.data
        email=form_reg.username.data
        password=sha256_crypt().encrypt(str(form_reg.password.data))
        #create cursor
        cur=mysql.connection.cursor()
        cur.execute("INSERT INTO users(username,email,password) VALUES(%s,%s,%s)",(username,email,password))
        #commit to db
        mysql.connection.commit()
        cur.close()
        flash('Register successfully,returning to home page...','success')
        #jump to home if success
        redirect(url_for('/home'))
        return render_template('register.html',user=userinfo)
    return render_template('register.html',form=form_reg,user=userinfo)

附件是我关于错误的截图,希望对你有帮助:

有什么我可以尝试的想法吗?

如有任何帮助,我们将不胜感激!

查看 passlib's documentation encrypt() 方法将 secret 作为参数并且此 secret 必须是 unicode 或 bytes:

classmethod PasswordHash.encrypt(secret, **kwds)

参数:

secret(unicode 或 bytes)——包含要编码的密码的字符串。

如果它 不是 unicode 或 bytes 此方法将抛出一个 TypeError 正如您在屏幕截图中看到的那样:

类型错误:

  • 如果机密不是 unicode 或字节。
  • 如果关键字参数的类型不正确。
  • 如果未提供必需的关键字。

您可以尝试将您的密码字符串编码为 Unicode,然后再尝试调用 encrypt() 方法并查看这是否可以解决您的错误。大致如下:

password_utf=form_reg.password.data.encode()
password = sha256_crypt().encrypt(password_utf)

或者,也许您可​​以尝试像下面这样散列您的表单密码:

# generate new salt, hash password

password = sha256_crypt.hash(form_reg.password.data))

希望对您有所帮助!