With python3, I have found a solution which is working for me:
import base64
userpass = username + ':' + password
encoded_u = base64.b64encode(userpass.encode()).decode()
headers = {"Authorization" : "Basic %s" % encoded_u}
To explain let's use interpreter:
>>> import base64
>>> userpass = "usrname:pass"
>>> print(base64.b64encode(userpass.encode()).decode())
dXNybmFtZTpwYXNzn #That is fine b64 string
>>> print(base64.b64encode(userpass.encode()))
b'dXNybmFtZTpwYXNz' #this is byte code
>>> print(base64.b64encode(userpass))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/[email protected]/3.10.7/Frameworks. /Python.framework/Versions/3.10/lib/python3.10/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
You can see that base64.b64encode requires byte type and return bytetype so we have to use builtin decode() and encode() https://www.programiz.com/python-programming/methods/string/encode func to give the bytecode and to get the string again