本文介绍 Python Requests 库的开发者接口,主要内容包括:python
目录json
1、主要接口缓存
1. requests.request()服务器
2. requests.head()、get()、post()、put()、patch()、delete()cookie
2、异常session
5、Response对象socket
6、Sessionide
1. requests.request(method, url, **kwargs)
构造并发送一个Request对象,返回一个Response对象。
参数:
示例:
>>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]>
2. requests.head(url, **kwargs)
发送一个 HEAD 请求,返回一个 Response 对象
参数:
3. requests.get(url, **kwargs)
发送一个 GET 请求,返回一个 Response 对象
参数:
4. requests.post(url, data=None, **kwargs)
发送一个 POST 请求,返回一个 Response 对象
参数:
5. requests.put(url, data=None, **kwargs)
发送一个 PUT 请求,返回一个 Response 对象
参数:
6. requests.patch(url, data=None, **kwargs)
发送一个 PUT 请求,返回一个 Response 对象
参数:
7. requests.delete(url, **kwargs)
发送一个 PUT 请求,返回一个 Response 对象
参数:
exception requests.RequestException
处理你的请求时出现了一个有歧义的异常
exception requests.ConnectionError
链接异常
exception requests.HTTPError(*args, **kwargs)
HTTP 错误
exception requests.URLRequired
无效的请求 URL
exception requests.TooManyRedirects
重定向过多
exception requests.exceptions.ConnectTimeout(*args, **kwargs)
The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
exception requests.exceptions.ReadTimeout(*args, **kwargs)
The server did not send any data in the allotted amount of time.
exception requests.exceptions.Timeout(*args, **kwargs)
请求超时限制,Catching this error will catch both ConnectTimeout and ReadTimeout errors.
requests.Request(method=None, url=None, headers=None, files=None, data={}, params={}, auth=None, cookies=None, hooks=None)
由用户建立的 Request 对象,用来准备一个 PreparedRequest 对象,后者被发给服务器
参数:
示例:
>>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]>
方法:
1. register_hook(event, hook)
注册一个事件钩子
2. deregister_hook(event, hook)
撤销一个已经注册的 hook,若是 hook 存在则返回 True,不然返回 False
3. prepare()
构造一个 PreparedRequest 对象用于传输,返回一个 PreparedRequest 对象
class requests.PreparedRequest
彻底可变的 PreparedRequest 对象,包含将会发送给服务器的字节,由 Request 或手动建立
示例:
>>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> r = req.prepare() <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]>
属性与方法:
1. body = None
发送给服务器的请求 body
2. deregister_hook(event, hook)
撤销一个已经注册的 hook,若是 hook 存在则返回 True,不然返回 False
3. headers = None
由HTTP headers构成的字典
4. hooks = None
dictionary of callback hooks, 仅供内部使用
5. method = None
HTTP 方法
6. path_url
构造要使用的路径URL
7. prepare(method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None)
用给定的参数准备整个请求
8. prepare_auth(auth, url='')
准备给定的 HTTP 认证数据
9. prepare_body(data, files, json=None)
准备给定的 HTTP body 数据
10. prepare_cookies(cookies)
准备给定的 HTTP cookie 数据
11. prepare_headers(headers)
准备给定的 HTTP headers
12. prepare_hooks(hooks)
准备给定的 hooks
13. prepare_method(method)
准备给定的 HTTP 方法
14. prepare_url(url, params)
准备给定的 HTTP URL
15. register_hook(event, hook)
适当地注册一个 hook
16. url = None
将请求发往的 HTTP URL
requests.Response
Response 对象,包含一个服务器对与 HTTP 请求的响应
属性与方法:
1. apparent_encoding
The apparent encoding, provided by the lovely Charade library (Thanks, Ian!).
2. content
以字节表示的响应内容
3. cookies = None
一个服务器发回的 cookie 的 CookieJar
4. elapsed = None
发出请求和接收到响应之间的时间间隔 (一个 timedelta)
5. encoding = None
访问r.text时要以何种编码方式解码
6. headers = None
大小写无关的响应头组成的字典,例如: headers['content-encoding'] 将会返回 'Content-Encoding' 响应头的值
7. history = None
A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.
8. iter_content(chunk_size=1, decode_unicode=False)
Iterates over the response data. This avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
9. iter_lines(chunk_size=512, decode_unicode=None)
Iterates over the response data, one line at a time. This avoids reading the content at once into memory for large responses.
10. json(**kwargs)
若是存在,返回JSON格式编码的响应内容
参数:
11. links
Returns the parsed header links of the response, if any.
12. raise_for_status()
Raises stored HTTPError, if one occurred.
13. raw = None
File-like object representation of response (for advanced usage). Requires that ``stream=True` on the request.
14. status_code = None
Integer Code of responded HTTP Status.
15. text
uncode格式的响应内容
若是 Response.encoding 是 None 且 chardet 模块可用,将会猜想响应的编码格式
16. url = None
响应的最终URL地址
requests.Session
一个 Requests 会话对象,提供 cookie 的存储,链接池和配置
示例:
>>> import requests >>> s = requests.Session() >>> s.get('http://httpbin.org/get') 200
属性与方法:
1. auth = None
附加到 Request 对象上的默认认证元组或对象
2. cert = None
SSL 证书的缺省值
3. close()
关闭全部的 adapters 和 session
4. delete(url, **kwargs)
发送一个 DELETE 请求,返回 Response 对象
参数:
5. get(url, **kwargs)
发送一个 GET 请求,返回 Response 对象
参数:
6. get_adapter(url)
返回给定URL的适当链接适配器
7. head(url, **kwargs)
发送一个 HEAD 请求,返回 Response 对象
参数:
8. headers = None
一个大小写不敏感的字典,包含了这个 Session 发出的全部 Request 对象都包含的 headers
9. hooks = None
事件处理 hook
10. max_redirects = None
最大重定向次数
11. mount(prefix, adapter)
将一个链接适配器注册到一个前缀上
12. options(url, **kwargs)
发送一个 OPTIONS 请求,返回 Response 对象
参数:
13. params = None
Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.
14. patch(url, data=None, **kwargs)
发送一个 PATCH 请求,返回 Response 对象
参数:
15. post(url, data=None, **kwargs)
发送一个 POST 请求,返回 Response 对象
参数:
16. proxies = None
字典,将协议映射为每一个Request使用的代理URL地址(例如: {‘http’: ‘foo.bar:3128’})
17. put(url, data=None, **kwargs)
发送一个 PUT 请求,返回 Response 对象
参数:
18. resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None)
接受一个 Response,返回一个 Responses 的 generator
19. send(request, **kwargs)
发送一个给定的 PreparedRequest 对象
20. stream = None
流式响应内容
21. trust_env = None
是否信任环境
22. verify = None
SSL 验证的默认值
class requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10, max_retries=0, pool_block=False)
针对 urllib3 的内置 HTTP Adapter,经过实现传输适配器接口,为 session 和 HTTP、 HTTPS链接提供了一个通用的接口。该类的实例一般由内部包裹下的Session类建立。
参数:
示例:
>>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a)
方法:
1. add_headers(request, **kwargs)
添加须要的 header,用户代码中不该该调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
2. build_response(req, resp)
从一个 urllib3 响应构建一个Response对象,用户代码中不应调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
3. cert_verify(conn, url, verify, cert)
验证一个 SSL 证书,用户代码中不应调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
4. close()
处理掉全部的内部状态
当前该方法仅仅关闭 PoolManager 进而断开池中的链接
5. get_connection(url, proxies=None)
对于给定的URL,返回一个 urllib3 链接。 用户代码中不应调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
url – 要链接的URL
proxies – (可选) 一个 Requests 风格的字典,内容是这次请求使用的代理
6. init_poolmanager(connections, maxsize, block=False, **pool_kwargs)
初始化一个 urllib3 PoolManager 实例
用户代码中不应调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
7. proxy_headers(proxy)
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used.
用户代码中不应调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
8. proxy_manager_for(proxy, **proxy_kwargs)
返回给定代理的 urllib3 ProxyManager 对象,用户代码中不应调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
返回:
ProxyManager
9. request_url(request, proxies)
获取最后一个请求的url,若是消息是由HTTP代理发送的,则必须使用完整的URL,不然只须要使用URL的路径部分
用户代码中不应调用该方法,该方法应该只在 HTTPAdapter 的子类中使用
参数:
10. send(request, stream=False, timeout=None, verify=True, cert=None, proxies=None)
发送 PreparedRequest 对象,返回 Response 对象
参数:
class requests.auth.AuthBase
全部认证的基类
class requests.auth.HTTPBasicAuth(username, password)
将 HTTP Basic Authentication 附加到给定的 Request 对象
class requests.auth.HTTPProxyAuth(username, password)
将 HTTP Proxy Authentication 附加到给定的 Request 对象
class requests.auth.HTTPDigestAuth(username, password)
将 HTTP Digest Authentication 附加到给定的 Request 对象
requests.utils.get_encodings_from_content(content)
返回给定内容的编码格式
参数:
requests.utils.get_encoding_from_headers(headers)
根据给定的 HTTP Header 字典返回编码格式
参数:
requests.utils.get_unicode_from_response(r)
以 unicode 返回响应内容
参数:
尝试:
requests.codes()
查询状态码字典中对应的键/值
>>> requests.codes['temporary_redirect'] 307 >>> requests.codes.teapot 418 >>> requests.codes['\o/'] 200