Skip to content
Myr

Merge pull request #1298 from Lukasa/adapter_doc

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Transport Adapter Docs

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 5b937b3, e5f1053 · Browse files · 3 files+126 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+126 added−14 removed

  • other:+126 added−14 removed

3 files+126 added−14 removed

modified:docs/user/advanced.rst+44 added-8 removed
78 unmodified lines
7980Prepared Requests81-----------------8283Whenever you receive a :class:`Response <requests.models.Response>` object 84from an API call or a Session call, the ``request`` attribute is actually the 85``PreparedRequest`` that was used. In some cases you may wish to do some extra 86work to the body or headers (or anything else really) before sending a 83Whenever you receive a :class:`Response <requests.models.Response>` object84from an API call or a Session call, the ``request`` attribute is actually the85``PreparedRequest`` that was used. In some cases you may wish to do some extra86work to the body or headers (or anything else really) before sending a87request. The simple recipe for this is the following::8889 from requests import Request, Session90
15 unmodified lines
106 # etc.107 )108 print(resp.status_code)109110Since you are not doing anything special with the ``Request`` object, you 111prepare it immediately and modified the ``PreparedRequest`` object. You then 112send that with the other parameters you would have sent to ``requests.*`` or 113``Sesssion.*``. 110Since you are not doing anything special with the ``Request`` object, you111prepare it immediately and modified the ``PreparedRequest`` object. You then112send that with the other parameters you would have sent to ``requests.*`` or113``Sesssion.*``.114115SSL Cert Verification116---------------------117
418 unmodified lines
536537 >>> r.links["last"]538 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}539540Transport Adapters541------------------542543As of v1.0.0, Requests has moved to a modular internal design. Part of the544reason this was done was to implement Transport Adapters, originally545`described here`_. Transport Adapters provide a mechanism to define interaction546methods for an HTTP service. In particular, they allow you to apply per-service547configuration.548549Requests ships with a single Transport Adapter, the550:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This adapter provides the551default Requests interaction with HTTP and HTTPS using the powerful `urllib3`_552library. Whenever a Requests :class:`Session <Session>` is initialized, one of553these is attached to the :class:`Session <Session>` object for HTTP, and one554for HTTPS.555556Requests enables users to create and use their own Transport Adapters that557provide specific functionality. Once created, a Transport Adapter can be558mounted to a Session object, along with an indication of which web services559it should apply to.560561::562563 >>> s = requests.Session()564 >>> s.mount('http://www.github.com', MyAdapter())565566The mount call registers a specific instance of a Transport Adapter to a567prefix. Once mounted, any HTTP request made using that session whose URL starts568with the given prefix will use the given Transport Adapter.569570Implementing a Transport Adapter is beyond the scope of this documentation, but571a good start would be to subclass the ``requests.adapters.BaseAdapter`` class.572573.. _`described here`: http://kennethreitz.org/exposures/the-future-of-python-http574.. _`urllib3`: https://github.com/shazow/urllib3575
modified:docs/api.rst+6 added
39 unmodified lines
4041.. autoclass:: Session42 :inherited-members:4344.. autoclass:: requests.adapters.HTTPAdapter45 :inherited-members:464748Exceptions49~~~~~~~~~~5051.. module:: requests
54 unmodified lines
106107.. autoclass:: requests.Session108 :inherited-members:109110.. autoclass:: requests.adapters.HTTPAdapter111 :inherited-members:112113114Migrating to 1.x115----------------116117This section details the main differences between 0.x and 1.x and is meant
66 unmodified lines
modified:requests/adapters.py+76 added-6 removed
41 unmodified lines
42 raise NotImplementedError434445class HTTPAdapter(BaseAdapter):46 """Built-In HTTP Adapter for Urllib3."""46 """The built-in HTTP Adapter for urllib3.4748 Provides a general-case interface for Requests sessions to contact HTTP and49 HTTPS urls by implementing the Transport Adapter interface. This class will50 usually be created by the :class:`Session <Session>` class under the51 covers.5253 :param pool_connections: The number of urllib3 connection pools to cache.54 :param pool_maxsize: The maximum number of connections to save in the pool.5556 Usage::5758 >>> import requests59 >>> s = requests.Session()60 >>> a = requests.adapters.HTTPAdapter()61 >>> s.mount('http://', a)62 """63 __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize']6465 def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE):66 self.max_retries = DEFAULT_RETRIES
16 unmodified lines
8384 self.init_poolmanager(self._pool_connections, self._pool_maxsize)8586 def init_poolmanager(self, connections, maxsize):87 """Initializes a urllib3 PoolManager. This method should not be called88 from user code, and is only exposed for use when subclassing the89 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.9091 :param connections: The number of urllib3 connection pools to cache.92 :param maxsize: The maximum number of connections to save in the pool.93 """94 # save these values for pickling95 self._pool_connections = connections96 self._pool_maxsize = maxsize9798 self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize)99100 def cert_verify(self, conn, url, verify, cert):101 """Verify a SSL certificate. This method should not be called from user102 code, and is only exposed for use when subclassing the103 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.104105 :param conn: The urllib3 connection object associated with the cert.106 :param url: The requested URL.107 :param verify: Whether we should actually verify the certificate.108 :param cert: The SSL certificate to verify.109 """110 if url.startswith('https') and verify:111112 cert_loc = None113
20 unmodified lines
134 else:135 conn.cert_file = cert136137 def build_response(self, req, resp):138 """Builds a :class:`Response <requests.Response>` object from a urllib3139 response. This should not be called from user code, and is only exposed140 for use when subclassing the141 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`142143 :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.144 :param resp: The urllib3 response object.145 """146 response = Response()147148 # Fallback to None if there's no status_code, for whatever reason.149 response.status_code = getattr(resp, 'status', None)
20 unmodified lines
170171 return response172173 def get_connection(self, url, proxies=None):134 """Returns a connection for the given URL."""174 """Returns a urllib3 connection for the given URL. This should not be175 called from user code, and is only exposed for use when subclassing the176 :class:`HTTPAdapter <reqeusts.adapters.HTTPAdapter>`.177178 :param url: The URL to connect to.179 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.180 """181 proxies = proxies or {}182 proxy = proxies.get(urlparse(url).scheme)183184 if proxy:
4 unmodified lines
189190 return conn191192 def close(self):147 """Dispose of any internal state.193 """Disposes of any internal state.194195 Currently, this just closes the PoolManager, which closes pooled196 connections.197 """
2 unmodified lines
200 def request_url(self, request, proxies):201 """Obtain the url to use when making the final request.202203 If the message is being sent through a proxy, the full URL has to be158 used. Otherwise, we should only use the path portion of the URL."""204 used. Otherwise, we should only use the path portion of the URL.205206 This shoudl not be called from user code, and is only exposed for use207 when subclassing the208 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.209210 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.211 :param proxies: A dictionary of schemes to proxy URLs.212 """213 proxies = proxies or {}214 proxy = proxies.get(urlparse(request.url).scheme)215216 if proxy:
4 unmodified lines
221 return url222223 def add_headers(self, request, **kwargs):224 """Add any headers needed by the connection. Currently this adds a171 Proxy-Authorization header."""225 Proxy-Authorization header.226227 This should not be called from user code, and is only exposed for use228 when subclassing the229 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.230231 :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.232 :param kwargs: The keyword arguments from the call to send().233 """234 proxies = kwargs.get('proxies', {})235236 if proxies is None:237 proxies = {}
9 unmodified lines
247 request.headers['Proxy-Authorization'] = _basic_auth_str(username,248 password)249250 def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):189 """Sends PreparedRequest object. Returns Response object."""251 """Sends PreparedRequest object. Returns Response object.252253 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.254 :param stream: (optional) Whether to stream the request content.255 :param timeout: (optional) The timeout on the request.256 :param verify: (optional) Whether to verify SSL certificates.257 :param vert: (optional) Any user-provided SSL certificate to be trusted.258 :param proxies: (optional) The proxies dictionary to apply to the request.259 """260261 conn = self.get_connection(request.url, proxies)262263 self.cert_verify(conn, request.url, verify, cert)264 url = self.request_url(request, proxies)
67 unmodified lines