Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python错误';字节';对象没有属性';编码';_Python_Bcrypt - Fatal编程技术网

Python错误';字节';对象没有属性';编码';

Python错误';字节';对象没有属性';编码';,python,bcrypt,Python,Bcrypt,我有这段代码,我使用的是python 3.7 def hash_password(password): return bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt()) def credentials_valid(username, password): with session_scope() as s: user = s.query(User).filter(User.name.in_([use

我有这段代码,我使用的是python 3.7

def hash_password(password):
    return bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())


def credentials_valid(username, password):
    with session_scope() as s:
        user = s.query(User).filter(User.name.in_([username])).first()
        if user:
            return bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8'))
        else:
            return False
但当我尝试运行时,会出现以下错误:

return bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8'))
AttributeError: 'bytes' object has no attribute 'encode'
bcrypt函数接受编码输入

您的两个参数password和hash_password(如果是unicode格式)需要进行编码。这就是你所做的。
但是,您为函数提供的“password”参数似乎已经编码为Python解释器提供的AttributeError

查看此工作实现:

import bcrypt

password = "asd123"
hashed_password_encoded = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
hashed_password = hashed_password_encoded.decode("utf8")

is_valid = bcrypt.checkpw(password.encode('utf8'), hashed_password.encode('utf8'))
print(is_valid)

密码变量的类型是什么?我想错误是:s
AttributeError:“bytes”对象没有属性“encode”
您不能将byte编码为byteHi,我从SQLite数据库获取密码。朋友,我从SQLite数据库获取密码。@andershernandez如果您是(并且应该是这样的话)将密码加密存储在unicode而不是字节中,然后需要执行
password.encode('utf8')
将其转换为字节。然而,如果以字节为单位存储密码,则无需再次对其进行编码。