我正在跟踪flask
上有关Youtube
的教程,以建立自己的网站。但是,即使我按照视频中的说明进行了每个步骤,也会出现错误。
我的操作系统是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)
关于我可以尝试的任何想法吗?
任何帮助将不胜感激!
答案 0 :(得分:1)
查看passlib's
documentation的encrypt()
方法以secret
作为参数,并且此秘密必须为unicode或字节:
classmethod PasswordHash.encrypt(secret, **kwds)
参数:
秘密(unicode或字节)–包含要编码的密码的字符串。
如果不是unicode或字节,则此方法将抛出 TypeError ,如您在屏幕快照中所见:
TypeError:
在尝试调用encrypt()
方法并查看是否可以解决错误之前,您可以尝试将密码字符串编码为Unicode 。类似于:
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))
希望有帮助!