Python3中Base64编码和解码,使用的是base64模块中的b64encode 和 b64decode方法,关于怎么使用,首先查看源码中的说明:
b64encode:
Encode the bytes-like object s using Base64 and return a bytes objectb64decode:
Decode the Base64 encoded bytes-like object or ASCII string s… The result is returned as a bytes object.
要点:
b64encode,入参是bytes-like object,出参是 bytes object
b64decode,入参是bytes-like object or ASCII string,出参是 bytes object
我们一般经常使用的是string或dict类型,因此在使用前后,还需要进行处理。
b64encode入参处理:
b64encode和b64decode出参处理:
整体代码如下:
import base64
import json
def str2base64(data)
en = base64.b64encode(data.encode('utf-8'))
return str(en,'utf8')
def base642str(base64_str):
de = base64.b64decode(base64_str)
return str(de,'utf8')
data_str='{"name":"abc","age":20,"info":{"order":[{"apple":2,"pear":3}]}}'
data_dict={"name":"abc","age":20,"info":{"order":[{"apple":2,"pear":3}]}}
# data_str为字符串
result_1=str2base64(data_str)
print(result_1)
# data_dict为字典,先将字典转为字符串,使用separators=(',',':')去除空格
data_new=json.dumps(data_dict, separators=(',',':'))
result_2=str2base64(data_new)
print(result_2)
# base64解码
result_3=base642str(result_1)
print(result_3)
result_4=base642str(result_2)
print(result_4)
执行结果
eyJuYW1lIjoiYWJjIiwiYWdlIjoyMCwiaW5mbyI6eyJvcmRlciI6W3siYXBwbGUiOjIsInBlYXIiOjN9XX19
eyJuYW1lIjoiYWJjIiwiYWdlIjoyMCwiaW5mbyI6eyJvcmRlciI6W3siYXBwbGUiOjIsInBlYXIiOjN9XX19
{"name":"abc","age":20,"info":{"order":[{"apple":2,"pear":3}]}}
{"name":"abc","age":20,"info":{"order":[{"apple":2,"pear":3}]}}