1
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'

I got this error to relate to Base64 in Python

This is my 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"}

and 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

I tried this solution and nothing work AttributeError: 'bytes' object has no attribute 'encode'; base64 encode a pdf file

3
  • I know that I decode bytes and encode strings, but i tried multiple solutions and nothing work with me Commented Jul 15, 2021 at 0:20
  • There is nothing in the code you've shown that has anything to do with Base64, and I don't understand why you would expect it to be relevant here. Commented Jul 15, 2021 at 0:21
  • 2
    "I know that I decode bytes and encode strings" Well, what happened when you tried thinking about a) which of those you have in each case; b) which of those you want in each case? If you have a bytes and want a bytes, what should you do to convert it? Commented Jul 15, 2021 at 0:22

1 Answer 1

3

When you encode something you are converting something into bytes, the problem here is that you already have bytes so python is telling that you cant encode that bytes because they are already encoded.

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

This is ok because im converting str into bytes

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

This will raise an error because my_encoded_string is already encoded

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Sergio, i got it and its work for me now I understand the converting on this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.