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 已经被编码