scorpion
scorpion

Reputation: 247

Python: Encode base64 string to put it on headers

I'm using this code for encode user_name and password and put it to headers.

def login_as_user(self,user):
    encode_login = base64.b64encode(bytes(str(user['email'] + ":" +user['password']),'utf8'))
    headers = { Config.API_AUTHORIZATION:"Basic "+str(encode_login)}
    response = requests.requestd("POST", self.url_path , data="", headers=headers)
    return response

With the

user_name = [email protected] and password = 1.

When I converted encode_login to str , the output always b'dGVzdEB0ZXN0LmNvbTox' , then when convert to string, it include b'. This makes my headers when requesting is wrong.

Please help, how can I solve this? Thanks.

Upvotes: 0

Views: 2242

Answers (1)

Chiheb Nexus
Chiheb Nexus

Reputation: 9267

You can simply decode your data to UTF8 by using decode().

For example, if your variable is:

a = b'dGVzdEB0ZXN0LmNvbTox'
# Or:
# a = a.decode('UTF8') 
a = a.decode()
print(a)

Output:

>> 'dGVzdEB0ZXN0LmNvbTox'

Otherwise, this will print:

base64.b64encode(bytes("hello", 'utf8')).decode()
>>> 'aGVsbG8='

So, in your question, you have just to modify this line:

headers = { Config.API_AUTHORIZATION:"Basic " + str(encode_login)}

By:

headers = { Config.API_AUTHORIZATION:"Basic " + encode_login.decode()}

Upvotes: 3

Related Questions