以下内容为Request官方翻译文档最后一部分内容
Response Headers(响应头)
我们可以看到,服务器响应的头信息是一个 Python 字典:
r.headers
# {
# 'content-encoding': 'gzip',
# 'transfer-encoding': 'chunked',
# 'connection': 'close',
# 'server': 'nginx/1.0.4',
# 'x-runtime': '148ms',
# 'etag': '"e1ca502697e5c9317743dc078f67693f"',
# 'content-type': 'application/json'
# }
不过,这个字典很特别:它是专门为 HTTP 头信息设计的。根据RFC 7230,HTTP表头名称 不区分大小写。
因此,我们可以使用我们想要的任何大写来访问标头:
r.headers['Content-Type']
# 'application/json'
r.headers.get('content-type')
# 'application/json'
它的特殊之处还在于服务器可以发送多个相同的表头 但时间不同的值,但 Requests 将它们组合起来,以便它们可以 表示在字典中的单个映射,如 RFC 7230:
接收者可以将具有相同字段名称的多个表头字段组合成一个"字段-name:字段-value"对,而不改变消息的语义学,通过按顺序将每个后续字段值附加到组合字段值,用逗号分隔。
Cookies
如果响应中包含了一些 Cookies 信息,你可以快速的访问到他们:
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']
# 'example_cookie_value'
要将您自己的cookie发送到服务器,您可以使用cookies 参数:
url = 'https://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
r.text
# '{"cookies": {"cookies_are": "working"}}'
Cookie在RequestsCookieJar, 它就像一个dict,但也提供了一个更完整的接口, 适合在多个域(domain)或路径(path)上使用。CookieJar 也可以被传递给 Requests 当做参数:
jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'https://httpbin.org/cookies'
r = requests.get(url, cookies=jar)
r.text
# '{"cookies": {"tasty_cookie": "yum"}}'
Redirection and History (重定向和访问历史)
默认情况下,Requests 将对除 HEAD 之外的所有动作执行重定向。
我们可以使用 Response 对象中的 history 属性来追踪重定向。
在Response.history 列表中包含请求完成后的 Response 对象,并且按从旧到最新排列。
例如, GitHub将所有HTTP请求重定向到安全超文本传输协议:
r = requests.get('http://github.com/')
r.url
# 'https://github.com/'
r.status_code
# 200
r.history
# [<Response [301]>]
如果使用GET、OPTIONS、POST、PUT、PATCH或DELETE,则可以使用allow_redirects参数禁用重定向处理:
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code
# 301
r.history
# []
如果您使用的是HEAD,您也可以启用重定向:
r = requests.head('http://github.com/', allow_redirects=True)
r.url
'https://github.com/'
r.history
[<Response [301]>]
Timeouts (超时)
你可以告诉 Requests 在给定的超时时间后停止响应等待,在生产代码中,应该在所有的请求中使用超时参数,如果不这样做的话,可能会导致你的程序无限期的挂起。
requests.get('https://github.com/', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
Errors and Exceptions (错误和异常)
如果出现网络问题(例如域名系统故障、拒绝连接等), 请求将引发ConnectionError异常。
Response.raise_for_status()将 如果HTTPError引发HTTPError 返回不成功的状态码。
如果请求超时,将抛出Timeout异常。
如果请求超过配置的最大重定向数,则 TooManyRedirects异常被抛出。
Requests 所有显式抛出的异常都继承自 requests.exceptions.RequestException。
本文暂时没有评论,来添加一个吧(●'◡'●)