Requests 工具带

这只是一组 python-requests 的实用程序,但并不真正属于 requests 本身。最低测试请求版本是 2.1.0。实际上,工具带也应该适用于 2.0.1,但一些特殊性阻止了对该版本进行有效或合理的测试。

pip install requests-toolbelt 开始使用!

multipart/form-data 编码器

主要功能是一个流式 multipart 表单数据对象,MultipartEncoder。其 API 如下所示

from requests_toolbelt import MultipartEncoder
import requests

m = MultipartEncoder(
    fields={'field0': 'value', 'field1': 'value',
            'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
    )

r = requests.post('http://httpbin.org/post', data=m,
                  headers={'Content-Type': m.content_type})

你还可以对不需要文件的请求使用 multipart/form-data 编码

from requests_toolbelt import MultipartEncoder
import requests

m = MultipartEncoder(fields={'field0': 'value', 'field1': 'value'})

r = requests.post('http://httpbin.org/post', data=m,
                  headers={'Content-Type': m.content_type})

或者,你也可以只创建字符串并检查数据

# Assuming `m` is one of the above
m.to_string()  # Always returns unicode

User-Agent 构造函数

你可以轻松构建一个 requests 样式的 User-Agent 字符串

from requests_toolbelt import user_agent

headers = {
    'User-Agent': user_agent('my_package', '0.0.1')
    }

r = requests.get('https://api.github.com/users', headers=headers)

SSLAdapter

SSLAdapter 最初发布在 Cory Benfield 的博客 上。此适配器允许用户为传出 HTTPS 连接选择 Python 的 ssl 模块中提供的 SSL 协议之一

from requests_toolbelt import SSLAdapter
import requests
import ssl

s = requests.Session()
s.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1))

cookies/ForgetfulCookieJar

ForgetfulCookieJar 阻止特定的请求会话存储 cookie

from requests_toolbelt.cookies.forgetful import ForgetfulCookieJar

session = requests.Session()
session.cookies = ForgetfulCookieJar()

贡献

请阅读 建议的工作流 以了解如何为该项目做出贡献。

请在 问题跟踪器 上报告任何错误