接着上一篇的翻译以下是文档中部内容
Custom Headers(自定义请求头)
如果你想自定义一个 HTTP 请求头,只需要将一个字典数据(dict)传到 headers 参数中即可。
例如,在前边的示例中,我们没有指定 user-agent:
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
注意:自定义请求头的优先级要低于一些特殊的数据,例如
- Authorization headers set with headers= will be overridden if credentials are specified in .netrc, which in turn will be overridden by the auth= parameter. Requests will search for the netrc file at ~/.netrc, ~/_netrc, or at the path specified by the NETRC environment variable.
- Authorization headers will be removed if you get redirected off-host.
- Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.
- Content-Length headers will be overridden when we can determine the length of the content.
此外,Requests 根本不会根据指定的自定义标头更改其行为。标头只是传递到最终请求中。
注意:所有标头值都必须是 string、bytestring 或 unicode。虽然允许,但建议避免传递 unicode 标头值。
More complicated POST requests (更复杂的 POST 请求)
通常,你可能想发送一些表单类型的数据,类似网页 form 表单。为了实现这个功能,你只需要将字典数据传递给 data 参数即可,此时,你的字典参数就被会自动的进行表单编码:
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post('https://httpbin.org/post', data=payload)
print(r.text)
# {
# ...
# "form": {
# "key2": "value2",
# "key1": "value1"
# },
# ...
# }
对于每个关键字,data 参数也可以有多个值,这可以通过使用元祖列表或者带有列表的字典来完成。当表单有多个元素时,使用相同的 key 是非常有用的。
# 使用元祖列表
payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
# 使用字典数组
payload_dict = {'key1': ['value1', 'value2']}
r2 = requests.post('https://httpbin.org/post', data=payload_dict)
print(r1.text)
# {
# ...
# "form": {
# "key1": [
# "value1",
# "value2"
# ]
# },
# ...
# }
r1.text == r2.text
# True
有时,你可能想直接发送非格式数据( not form-encoded),如果你传入了一个 string 而不是 dict,数据将直接发布。
例如: GitHub API v3接受JSON-Encoded POST/PATCH数据:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
# 发送JSON数据
r = requests.post(url, data=json.dumps(payload))
需要注意的是, 上边的代码不会添加Content-Type表头 (特别是它不会将其设置为application/json)。
如果你需要那个表头集,而且你不想自己编码dict, 也可以使用json参数直接传递(在版本2.4.2中添加) 它会自动编码:
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)
请注意,如果传递了data或files,则忽略json参数。
POST a Multipart-Encoded File (POST一个多部分编码的文件)
Requests 可以非常容易的实现文件上传:
url = 'https://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text
# {
# ...
# "files": {
# "file": "<censored...binary...data>"
# },
# ...
# }
可以显式设置文件名、content_type和标题:
url = 'https://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
r.text
# {
# ...
# "files": {
# "file": "<censored...binary...data>"
# },
# ...
# }
如果需要,可以发送要作为文件接收的字符串:
url = 'https://httpbin.org/post'
files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
r = requests.post(url, files=files)
r.text
# {
# ...
# "files": {
# "file": "some,data,to,send\\nanother,row,to,send\\n"
# },
# ...
# }
如果您发布的是一个非常大的文件作为multipart/form-data 请求,您可能想要流式传输请求。默认情况下,requests不会 支持这个,但有一个单独的包可以- requests-toolbelt。
强烈建议您以二进制模式打开文件。这是因为请求可能会尝试提供 你Content-Length表头,如果它有这个值 将被设置为文件中的字节数。可能会发生错误 如果您以文本模式打开文件。
Response Status Codes(响应状态码)
我们可以查看响应状态码:
r = requests.get('https://httpbin.org/get')
r.status_code
# 200
Requests 还带有一个内置的状态代码查找对象,便于参考:
r.status_code == requests.codes.ok
# True
如果我们获取了一个错误的请求(4XX客户端错误或5XX服务器错误响应),我们 可以用Response.raise_for_status():
bad_r = requests.get('https://httpbin.org/status/404')
bad_r.status_code
# 404
bad_r.raise_for_status()
# Traceback (most recent call last):
# File "requests/models.py", line 832, in raise_for_status
# raise http_error
# requests.exceptions.HTTPError: 404 Client Error
但是当我们从 r 中获取到的 status_code 为 200 时,我们调用 raise_for_status()会获取到 None:
r.raise_for_status()
# None
而不会产生任何错误。
本文暂时没有评论,来添加一个吧(●'◡'●)