Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encoding in python3

my script includes this line:

encoded = "Basic " + s.encode("base64").rstrip()

But gives me back the error:

LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

This line seemed to work fine in python 2 but since switching to 3 I get the error

like image 554
Sam Nixey Avatar asked Oct 03 '17 14:10

Sam Nixey


2 Answers

This string codec was removed in Python 3. Use base64 module:

Python 3.6.1 (default, Mar 23 2017, 16:49:06)

>>> import base64
>>> base64.b64encode('whatever')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
>>> base64.b64encode(b'whatever')
b'd2hhdGV2ZXI='
>>>

Don't forget to convert the data to bytes.

like image 174
warvariuc Avatar answered Nov 13 '22 15:11

warvariuc


Code as follows:

base64.urlsafe_b64encode('Some String'.encode('UTF-8')).decode('ascii')

For example: return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}

Worked for me.

like image 33
Anuj Masand Avatar answered Nov 13 '22 13:11

Anuj Masand