Python3中Base64編碼和解碼,使用的是base64模塊中的b64encode 和 b64decode方法,關(guān)于怎么使用,首先查看源碼中的說明:
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.
要點(diǎn):
b64encode,入?yún)⑹莃ytes-like object,出參是 bytes object
b64decode,入?yún)⑹莃ytes-like object or ASCII string,出參是 bytes object
我們一般經(jīng)常使用的是string或dict類型,因此在使用前后,還需要進(jìn)行處理。
b64encode入?yún)⑻幚恚?/strong>
- 如果要編碼的是json字符串,要先轉(zhuǎn)為bytes object,需要使用字符串的encode()方法(該方法返回的是一個(gè)字節(jié)序列,即bytes 類型)
- 如果要編碼的是字典,可以先使用json.dumps(),將字典轉(zhuǎn)為字符串,然后再使用字符串的encode()方法。注意json.dumps()生成json,會(huì)在key和value之間默認(rèn)加個(gè)空格,需要使用separators=(‘,’,‘:’)去除。
b64encode和b64decode出參處理:
- 需要使用Python的內(nèi)置函數(shù)str(),將一個(gè)對象轉(zhuǎn)換為字符串格式
整體代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-546026.html
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為字典,先將字典轉(zhuǎn)為字符串,使用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)
執(zhí)行結(jié)果文章來源地址http://www.zghlxwxcb.cn/news/detail-546026.html
eyJuYW1lIjoiYWJjIiwiYWdlIjoyMCwiaW5mbyI6eyJvcmRlciI6W3siYXBwbGUiOjIsInBlYXIiOjN9XX19
eyJuYW1lIjoiYWJjIiwiYWdlIjoyMCwiaW5mbyI6eyJvcmRlciI6W3siYXBwbGUiOjIsInBlYXIiOjN9XX19
{"name":"abc","age":20,"info":{"order":[{"apple":2,"pear":3}]}}
{"name":"abc","age":20,"info":{"order":[{"apple":2,"pear":3}]}}
到了這里,關(guān)于Python中的Base64編碼和解碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!