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
Provenance
- Commit
2426eeb- Tree
17615a9- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
5b937b3- Parent 2
e5f1053
3 files changed+126 added−14 removed
modified:docs/user/advanced.rst+44 added-8 removed
78 unmodified lines79 80 Prepared Requests81 -----------------82 83-Whenever you receive a :class:`Response <requests.models.Response>` object 84-from 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 86-work to the body or headers (or anything else really) before sending a 83+Whenever you receive a :class:`Response <requests.models.Response>` object84+from 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 extra86+work to the body or headers (or anything else really) before sending a87 request. The simple recipe for this is the following::88 89 from requests import Request, Session90 15 unmodified lines106 # etc.107 )108 print(resp.status_code)109 110-Since you are not doing anything special with the ``Request`` object, you 111-prepare it immediately and modified the ``PreparedRequest`` object. You then 112-send that with the other parameters you would have sent to ``requests.*`` or 113-``Sesssion.*``. 110+Since you are not doing anything special with the ``Request`` object, you111+prepare it immediately and modified the ``PreparedRequest`` object. You then112+send that with the other parameters you would have sent to ``requests.*`` or113+``Sesssion.*``.114 115 SSL Cert Verification116 ---------------------117 418 unmodified lines536 537 >>> r.links["last"]538 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}539 540+Transport Adapters541+------------------542+543+As of v1.0.0, Requests has moved to a modular internal design. Part of the544+reason this was done was to implement Transport Adapters, originally545+`described here`_. Transport Adapters provide a mechanism to define interaction546+methods for an HTTP service. In particular, they allow you to apply per-service547+configuration.548+549+Requests ships with a single Transport Adapter, the550+:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This adapter provides the551+default Requests interaction with HTTP and HTTPS using the powerful `urllib3`_552+library. Whenever a Requests :class:`Session <Session>` is initialized, one of553+these is attached to the :class:`Session <Session>` object for HTTP, and one554+for HTTPS.555+556+Requests enables users to create and use their own Transport Adapters that557+provide specific functionality. Once created, a Transport Adapter can be558+mounted to a Session object, along with an indication of which web services559+it should apply to.560+561+::562+563+ >>> s = requests.Session()564+ >>> s.mount('http://www.github.com', MyAdapter())565+566+The mount call registers a specific instance of a Transport Adapter to a567+prefix. Once mounted, any HTTP request made using that session whose URL starts568+with the given prefix will use the given Transport Adapter.569+570+Implementing a Transport Adapter is beyond the scope of this documentation, but571+a good start would be to subclass the ``requests.adapters.BaseAdapter`` class.572+573+.. _`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 lines40 41 .. autoclass:: Session42 :inherited-members:43 44+.. autoclass:: requests.adapters.HTTPAdapter45+ :inherited-members:46 47+48 Exceptions49 ~~~~~~~~~~50 51 .. module:: requests54 unmodified lines106 107 .. autoclass:: requests.Session108 :inherited-members:109 110+.. autoclass:: requests.adapters.HTTPAdapter111+ :inherited-members:112 113+114 Migrating to 1.x115 ----------------116 117 This section details the main differences between 0.x and 1.x and is meant66 unmodified linesmodified:requests/adapters.py+76 added-6 removed
41 unmodified lines42 raise NotImplementedError43 44 45 class HTTPAdapter(BaseAdapter):46- """Built-In HTTP Adapter for Urllib3."""46+ """The built-in HTTP Adapter for urllib3.47+48+ 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.52+53+ :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.55+56+ Usage::57+58+ >>> 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']64 65 def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE):66 self.max_retries = DEFAULT_RETRIES16 unmodified lines83 84 self.init_poolmanager(self._pool_connections, self._pool_maxsize)85 86 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>`.90+91+ :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 = maxsize97 98 self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize)99 100 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>`.104+105+ :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:111 112 cert_loc = None113 20 unmodified lines134 else:135 conn.cert_file = cert136 137 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>`142+143+ :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.144+ :param resp: The urllib3 response object.145+ """146 response = Response()147 148 # Fallback to None if there's no status_code, for whatever reason.149 response.status_code = getattr(resp, 'status', None)20 unmodified lines170 171 return response172 173 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>`.177+178+ :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)183 184 if proxy:4 unmodified lines189 190 return conn191 192 def close(self):147- """Dispose of any internal state.193+ """Disposes of any internal state.194 195 Currently, this just closes the PoolManager, which closes pooled196 connections.197 """2 unmodified lines200 def request_url(self, request, proxies):201 """Obtain the url to use when making the final request.202 203 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.205+206+ This shoudl not be called from user code, and is only exposed for use207+ when subclassing the208+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.209+210+ :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)215 216 if proxy:4 unmodified lines221 return url222 223 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.226+227+ This should not be called from user code, and is only exposed for use228+ when subclassing the229+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.230+231+ :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', {})235 236 if proxies is None:237 proxies = {}9 unmodified lines247 request.headers['Proxy-Authorization'] = _basic_auth_str(username,248 password)249 250 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.252 253+ :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+ """260+261 conn = self.get_connection(request.url, proxies)262 263 self.cert_verify(conn, request.url, verify, cert)264 url = self.request_url(request, proxies)67 unmodified lines