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'