base64.py 模型提供了將二進制數據編碼爲可印刷的 ASCII 字符和將這些編碼後的數據返回到二進制數據的方法。
一、方法
b64encode
(s, altchars=None)
1. 使用 Base64 編碼類字節對象(bytes-like object),並返回編碼字節;
bytes-like object
An object that supports the Buffer Protocol and can export a C-contiguous buffer. This includes all
bytes
,bytearray
, andarray.array
objects, as well as many commonmemoryview
objects. Bytes-like objects can be used for various operations that work with binary data; these include compression, saving to a binary file, and sending over a socket.Some operations need the binary data to be mutable. The documentation often refers to these as “read-write bytes-like objects”. Example mutable buffer objects include
bytearray
and amemoryview
of abytearray
. Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”); examples of these includebytes
and amemoryview
of abytes
object.
2. altchars 參數必須有至少兩個類字節對象(bytes-like object),用來替換 '+' 和 '/' 等符號,默認 None 。
b64decode
(s, altchars=None, validate=False)
1. 解碼使用 Base64 編碼的類字節對象(bytes-like object)或者 ASCII 字符串,並返回解碼字節;
2. 同上;
3. 如果 validate 爲 False (默認值),則在填充檢查之前,將丟棄既不在普通的 base-64 字母表中也不在備用字母表中的字符。
- standard_b64encode(s)
編碼將採用標準的 Base64 字母表。
standard_b64decode
(s)
解碼將採用標準的 Base64 字母表。
urlsafe_b64encode
(s)
標準的 Base64 字母表使用 '/' 替換 '+' 和 '_' ,該方法使用 URL-safe 和 filesystem-safe 字母表,使用 '-' 替換 '+' 和 '_' 。最終結果仍然保留 '=' 。
urlsafe_b64decode
(s)
略
encode
(input, output)
將 input 文件編碼,並將 base64 編碼的結果寫入到 output 文件中。是通過 input.read() 讀取。
注意: input 和output 必須時文件對象;output 中每 76 個字節,encode() 方法都會插入一個換行符( b'\n' ),從而確保 output 都是以新的一行結束。
decode
(input, output)
將 input 文件解碼,並將解碼的結果寫入到 output 文件中。是通過 input.readline() 讀取。
二、舉例
>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'