微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AttributeError: 'bytes' 对象没有属性 'encode' Base64

如何解决AttributeError: 'bytes' 对象没有属性 'encode' Base64

File ".\core\users\login.py",line 22,in login_user
    db_user = crud.get_Login(
  File ".\api\crud.py",line 39,in get_Login
    db_user.password.encode('utf-8'))
AttributeError: 'bytes' object has no attribute 'encode'

这个错误与 Python 中的 Base64 相关

这是我的core\users\login.py

@router.post("/login")
def login_user(user: schemas.UserLogin,db: Session = Depends(get_db)):
    db_user = crud.get_Login(
        db,username=user.username,password=user.password)
    if db_user == False:
        raise HTTPException(status_code=400,detail="Wrong username/password")
    return {"message": "User found"}

api\crud.py

def get_Login(db: Session,username: str,password: str):
    db_user = db.query(models.UserInfo).filter(
        models.UserInfo.username == username).first()
    print(username,password)
    pwd = bcrypt.checkpw(password.encode('utf-8'),db_user.password.encode('utf-8'))
    return pwd

我尝试了这个解决方案,但没有任何效果 AttributeError: 'bytes' object has no attribute 'encode'; base64 encode a pdf file

解决方法

当你编码一些东西时,你正在将一些东西转换成字节,这里的问题是你已经有了字节,所以 python 告诉你不能对这些字节进行编码,因为它们已经被编码了。

my_string          = "Hello World!"
my_encoded_string  = my_string.encode('utf-8')

这没问题,因为我将 str 转换为字节

my_encoded_string  = my_string.encode('utf-8')
foo                = my_encoded_string.encode('utf-8')

这将引发错误,因为 my_encoded_string 已经被编码

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。