12.4 base64:用ASCII编码二进制数据
base64模块包含一些函数可以将二进制数据转换为适合使用纯文本协议传输的ASCII的一个子集,Base64,Base32,Base16和Base85编码将8位字节转换为ASCII可打印字符范围内的字符,留出更多的位来表示数据,包装与只支持ASCII数据的系统兼容,如SMTP。
base(进制)值对应各编码中使用的字母表长度。这些原始编码还有一些"URL安全"(URL-safe)的变形,其使用的字母表稍有不同。
12.4.1 Base64编码
一下代码清单给出了一个简单的例子,其中对一些文本进行了编码。
import base64
import textwrap
# Load this source file and strip the header.
with open(__file__,'r',encoding='utf-8') as input:
raw = input.read()
initial_data = raw.split('#end_pymotw_header')[1]
byte_string = initial_data.encode('utf-8')
encoded_data = base64.b64encode(byte_string)
num_initial = len(byte_string)
# There will never be more than 2 padding bytes.
padding = 3 - (num_initial % 3)
print('{} bytes before encoding'.format(num_initial))
print('Expect {} padding bytes'.format(padding))
print('{} bytes after encoding\n'.format(len(encoded_data)))
print(encoded_data)
输入必须是一个字节串,所以首先将Unicode字符串编码为UTF-8。输出显示了UTF-8源文件的185个字节在编码后扩展为248字节。
说明:由库生成的编码数据中并没有回车,不过这里的输出中人工增加了换行符,以便更美观地在页面上显示。