【问题标题】:AttributeError: 'bytes' object has no attribute 'encode' Base64AttributeError:“字节”对象没有属性“编码”Base64
【发布时间】:2021-07-15 00:18:28
【问题描述】:
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

【问题讨论】:

  • 我知道我 decode 字节和 encode 字符串,但我尝试了多种解决方案,但没有任何用处
  • 您展示的代码中没有任何内容与 Base64 有任何关系,我不明白您为什么会期望它与此处相关。
  • "我知道我 decode 字节和 encode 字符串" 好吧,当您尝试考虑 a) 在每种情况下您有哪些; b) 在每种情况下,您想要中的哪一个?如果你有一个bytes 并想要一个bytes,你应该怎么做才能转换它?

标签: python encoding crud bcrypt fastapi


【解决方案1】:

当您对某些内容进行编码时,您正在将某些内容转换为字节,这里的问题是您已经有了字节,所以 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 已编码

【讨论】:

  • 谢谢你,塞尔吉奥,我明白了,它现在对我有用,我明白了这个转换
猜你喜欢
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 2020-03-11
  • 2021-09-26
  • 2016-11-09
  • 2021-09-11
  • 2021-11-29
相关资源
最近更新 更多