模块介绍
base64
库是 Python 标准库的一部分,无需额外安装。它提供了用于将二进制数据编码为 base64 可打印 ASCII 文本的功能,以及相应的解码功能。base64 编码通常用于确保在基于文本的协议中传输数据时没有损失或误解。
适用于 Python 3.x 版本,无需额外安装即可使用。
应用场景
base64
库广泛应用于以下场景:
- Web 开发:在 HTTP 传输过程中,将二进制数据(如图片、文件)编码为文本格式,以便安全传输。
- 数据存储:将二进制数据保存为文本格式,以便嵌入到 XML 或 JSON 等格式文件中。
- 网络安全:用于生成基础认证的 token 或其他加密方式的前处理。
安装说明
因为 base64
是 Python 自带的标准库,所以不需要额外安装。只需确认 Python 环境即可使用:
用法举例
1. 编码和解码字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import base64
message = "Hello, Python!"
message_bytes = message.encode('utf-8')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('utf-8')
print(f"Encoded Message: {base64_message}")
base64_bytes = base64_message.encode('utf-8')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('utf-8')
print(f"Decoded Message: {message}")
|
2. 编码和解码文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import base64
def encode_file(file_path): with open(file_path, 'rb') as file: file_content = file.read() base64_encoded = base64.b64encode(file_content) return base64_encoded.decode('utf-8')
def decode_file(base64_content, output_path): file_content = base64.b64decode(base64_content) with open(output_path, 'wb') as file: file.write(file_content)
input_file = 'example.jpg' encoded_content = encode_file(input_file) print(f"Encoded file content: {encoded_content[:60]}...")
output_file = 'decoded_example.jpg' decode_file(encoded_content, output_file) print(f"File decoded and saved as: {output_file}")
|
3. 生成和解析 URL 安全的 token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import base64 import json
data = { 'username': 'travis', 'access_level': 'admin' }
json_string = json.dumps(data)
base64_encoded = base64.urlsafe_b64encode(json_string.encode('utf-8')).decode('utf-8') print(f"Encoded token: {base64_encoded}")
base64_decoded = base64.urlsafe_b64decode(base64_encoded)
decoded_data = json.loads(base64_decoded.decode('utf-8')) print(f"Decoded data: {decoded_data}")
|
强烈建议大家关注我的博客 —— 全糖冲击博客。我会不定期更新 Python 标准库和其他编程技术的详细教程。关注我的博客,您将能够以最快的速度获取最新的编程知识,并且所有内容都经过精心设计,旨在帮助您更好地理解和应用各类技术。不管您是编程新手还是有经验的开发者,我的博客都将是您获取高质量学习资源的最佳选择!
软件版本可能变动
如果本文档不再适用或有误,请留言或联系我进行更新。让我们一起营造良好的学习氛围。感谢您的支持! - Travis Tang