我的脚本包含以下行:
encoded = "Basic " + s.encode("base64").rstrip()
但是给了我错误的答案:
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs
这行似乎在python 2中工作正常但是由于切换到3我得到了错误
答案 0 :(得分:4)
此字符串编解码器已在Python 3中删除。使用base64
模块:
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='
>>>
不要忘记将数据转换为字节。
答案 1 :(得分:3)
代码如下:
base64.urlsafe_b64encode('Some String'.encode('UTF-8')).decode('ascii')
例如: return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}
为我工作。