Skip to content
Myr

advanced.rst

This file

Path

docs/user/advanced.rst

989 lines · 34.4 KiB

Last changed by

Merge pull request #3678 from nateprewitt/3675_streaming_docsCory Benfieldbefore adoption33bd38b

History of this file

Take it

The walk stopped after 200 commits: lines older than 6143b7e point at it.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 1–26why, one step back
1.. _advanced:
23Advanced Usage4==============56This document covers some of Requests more advanced features.78.. _session-objects:910Session Objects11---------------1213The Session object allows you to persist certain parameters across14requests. It also persists cookies across all requests made from the15Session instance, and will use ``urllib3``'s `connection pooling`_. So if16you're making several requests to the same host, the underlying TCP17connection will be reused, which can result in a significant performance18increase (see `HTTP persistent connection`_).1920A Session object has all the methods of the main Requests API.2122Let's persist some cookies across requests::2324 s = requests.Session()2526 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 27why, one step back
27 r = s.get('http://httpbin.org/cookies')

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 28–52why, one step back
28
29 print(r.text)30 # '{"cookies": {"sessioncookie": "123456789"}}'313233Sessions can also be used to provide default data to the request methods. This34is done by providing data to the properties on a Session object::3536 s = requests.Session()37 s.auth = ('user', 'pass')38 s.headers.update({'x-test': 'true'})3940 # both 'x-test' and 'x-test2' are sent41 s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})424344Any dictionaries that you pass to a request method will be merged with the45session-level values that are set. The method-level parameters override session46parameters.4748Note, however, that method-level parameters will *not* be persisted across49requests, even if using a session. This example will only send the cookies50with the first request, but not the second::5152 s = requests.Session()

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 53why, one step back
53

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 54–89why, one step back
54 r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})
55 print(r.text)56 # '{"cookies": {"from-my": "browser"}}'5758 r = s.get('http://httpbin.org/cookies')59 print(r.text)60 # '{"cookies": {}}'616263If you want to manually add cookies to your session, use the64:ref:`Cookie utility functions <api-cookies>` to manipulate65:attr:`Session.cookies <requests.Session.cookies>`.6667Sessions can also be used as context managers::6869 with requests.Session() as s:70 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')7172This will make sure the session is closed as soon as the ``with`` block is73exited, even if unhandled exceptions occurred.747576.. admonition:: Remove a Value From a Dict Parameter7778 Sometimes you'll want to omit session-level keys from a dict parameter. To79 do this, you simply set that key's value to ``None`` in the method-level80 parameter. It will automatically be omitted.8182All values that are contained within a session are directly available to you.83See the :ref:`Session API Docs <sessionapi>` to learn more.8485.. _request-and-response-objects:8687Request and Response Objects88----------------------------89

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 90why, one step back
90Whenever a call is made to ``requests.get()`` and friends, you are doing two

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 91–92why, one step back
91major things. First, you are constructing a ``Request`` object which will be
92sent off to a server to request or query some resource. Second, a ``Response``

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

lines 93–94why, one step back
93object is generated once Requests gets a response back from the server.
94The ``Response`` object contains all of the information returned by the server and

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 95–132why, one step back
95also contains the ``Request`` object you created originally. Here is a simple
96request to get some very important information from Wikipedia's servers::9798 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')99100If we want to access the headers the server sent back to us, we do this::101102 >>> r.headers103 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':104 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':105 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',106 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',107 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,108 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':109 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,110 MISS from cp1010.eqiad.wmnet:80'}111112However, if we want to get the headers we sent the server, we simply access the113request, and then the request's headers::114115 >>> r.request.headers116 {'Accept-Encoding': 'identity, deflate, compress, gzip',117 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}118119.. _prepared-requests:120121Prepared Requests122-----------------123124Whenever you receive a :class:`Response <requests.Response>` object125from an API call or a Session call, the ``request`` attribute is actually the126``PreparedRequest`` that was used. In some cases you may wish to do some extra127work to the body or headers (or anything else really) before sending a128request. The simple recipe for this is the following::129130 from requests import Request, Session131132 s = Session()

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

lines 133–134why, one step back
133
134 req = Request('POST', url, data=data, headers=headers)

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 135–137why, one step back
135 prepped = req.prepare()
136137 # do something with prepped.body

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

lines 138–139why, one step back
138 prepped.body = 'No, I want exactly this as the body.'
139

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 140why, one step back
140 # do something with prepped.headers

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 141why, one step back
141 del prepped.headers['Content-Type']

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 142–169why, one step back
142
143 resp = s.send(prepped,144 stream=stream,145 verify=verify,146 proxies=proxies,147 cert=cert,148 timeout=timeout149 )150151 print(resp.status_code)152153Since you are not doing anything special with the ``Request`` object, you154prepare it immediately and modify the ``PreparedRequest`` object. You then155send that with the other parameters you would have sent to ``requests.*`` or156``Session.*``.157158However, the above code will lose some of the advantages of having a Requests159:class:`Session <requests.Session>` object. In particular,160:class:`Session <requests.Session>`-level state such as cookies will161not get applied to your request. To get a162:class:`PreparedRequest <requests.PreparedRequest>` with that state163applied, replace the call to :meth:`Request.prepare()164<requests.Request.prepare>` with a call to165:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::166167 from requests import Request, Session168169 s = Session()

improve advanced.rstKenneth Reitzbefore adoptionf4445b3

line 170why, one step back
170 req = Request('GET', url, data=data, headers=headers)

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 171–174why, one step back
171
172 prepped = s.prepare_request(req)173174 # do something with prepped.body

improve advanced.rstKenneth Reitzbefore adoptionf4445b3

lines 175–176why, one step back
175 prepped.body = 'Seriously, send exactly these bytes.'
176

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 177why, one step back
177 # do something with prepped.headers

improve advanced.rstKenneth Reitzbefore adoptionf4445b3

line 178why, one step back
178 prepped.headers['Keep-Dead'] = 'parrot'

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 179–194why, one step back
179
180 resp = s.send(prepped,181 stream=stream,182 verify=verify,183 proxies=proxies,184 cert=cert,185 timeout=timeout186 )187188 print(resp.status_code)189190.. _verification:191192SSL Cert Verification193---------------------194

Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414

line 195why, one step back
195Requests verifies SSL certificates for HTTPS requests, just like a web browser.

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

line 196why, one step back
196By default, SSL verification is enabled, and Requests will throw a SSLError if

Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414

line 197why, one step back
197it's unable to verify the certificate::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 198why, one step back
198

Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414

lines 199–200why, one step back
199 >>> requests.get('https://requestb.in')
200 requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 201why, one step back
201

Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414

line 202why, one step back
202I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 203why, one step back
203

Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414

line 204why, one step back
204 >>> requests.get('https://github.com')

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 205–210why, one step back
205 <Response [200]>
206207You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::208209 >>> requests.get('https://github.com', verify='/path/to/certfile')210

Merge pull request #3539 from RichieB2B/ncsc-nl/docufixCory Benfieldbefore adoption889f855

lines 211–215why, one step back
211or persistent::
212213 s = requests.Session()214 s.verify = '/path/to/certfile'215

Document header ordering. (#3295)Cory Benfieldbefore adoption7a404cf

line 216why, one step back
216.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using

Merge pull request #3171 from luv/masterCory Benfieldbefore adoption989e8f1

lines 217–218why, one step back
217 the c_rehash utility supplied with OpenSSL.
218

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 219–220why, one step back
219This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.
220

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 221why, one step back
221Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 222–233why, one step back
222
223 >>> requests.get('https://kennethreitz.com', verify=False)224 <Response [200]>225226By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.227228You can also specify a local cert to use as client side certificate, as a single229file (containing the private key and the certificate) or as a tuple of both230file's path::231232 >>> requests.get('https://kennethreitz.com', cert=('/path/client.cert', '/path/client.key'))233 <Response [200]>

Merge pull request #3539 from RichieB2B/ncsc-nl/docufixCory Benfieldbefore adoption889f855

lines 234–238why, one step back
234
235or persistent::236237 s = requests.Session()238 s.cert = '/path/client.cert'

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 239why, one step back
239

Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414

line 240why, one step back
240If you specify a wrong path or an invalid cert, you'll get a SSLError::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 241–245why, one step back
241
242 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/client.pem')243 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib244245.. warning:: The private key to your local certificate *must* be unencrypted.

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

line 246why, one step back
246 Currently, Requests does not support using encrypted keys.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 247–252why, one step back
247
248.. _ca-certificates:249250CA Certificates251---------------252

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 253why, one step back
253By default, Requests bundles a set of root CAs that it trusts, sourced from the

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 254–265why, one step back
254`Mozilla trust store`_. However, these are only updated once for each Requests
255version. This means that if you pin a Requests version your certificates can256become extremely out of date.257258From Requests version 2.4.0 onwards, Requests will attempt to use certificates259from `certifi`_ if it is present on the system. This allows for users to update260their trusted certificates without having to change the code that runs on their261system.262263For the sake of security we recommend upgrading certifi frequently!264265.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection

Merge pull request #3604 from iamprakashom/masterCory Benfieldbefore adoption1ac56f1

line 266why, one step back
266.. _connection pooling: http://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 267–276why, one step back
267.. _certifi: http://certifi.io/
268.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt269270.. _body-content-workflow:271272Body Content Workflow273---------------------274275By default, when you make a request, the body of the response is downloaded276immediately. You can override this behaviour and defer downloading the response

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 277why, one step back
277body until you access the :attr:`Response.content <requests.Response.content>`

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 278–289why, one step back
278attribute with the ``stream`` parameter::
279280 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'281 r = requests.get(tarball_url, stream=True)282283At this point only the response headers have been downloaded and the connection284remains open, hence allowing us to make content retrieval conditional::285286 if int(r.headers['content-length']) < TOO_LONG:287 content = r.content288 ...289

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

lines 290–291why, one step back
290You can further control the workflow by use of the :meth:`Response.iter_content() <requests.Response.iter_content>`
291and :meth:`Response.iter_lines() <requests.Response.iter_lines>` methods.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 292–293why, one step back
292Alternatively, you can read the undecoded body from the underlying
293urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 294why, one step back
294:attr:`Response.raw <requests.Response.raw>`.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 295–297why, one step back
295
296If you set ``stream`` to ``True`` when making a request, Requests cannot297release the connection back to the pool unless you consume all the data or call

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 298why, one step back
298:meth:`Response.close <requests.Response.close>`. This can lead to

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 299–359why, one step back
299inefficiency with connections. If you find yourself partially reading request
300bodies (or not reading them at all) while using ``stream=True``, you should301consider using ``contextlib.closing`` (`documented here`_), like this::302303 from contextlib import closing304305 with closing(requests.get('http://httpbin.org/get', stream=True)) as r:306 # Do things with the response here.307308.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing309310.. _keep-alive:311312Keep-Alive313----------314315Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!316Any requests that you make within a session will automatically reuse the appropriate317connection!318319Note that connections are only released back to the pool for reuse once all body320data has been read; be sure to either set ``stream`` to ``False`` or read the321``content`` property of the ``Response`` object.322323.. _streaming-uploads:324325Streaming Uploads326-----------------327328Requests supports streaming uploads, which allow you to send large streams or329files without reading them into memory. To stream and upload, simply provide a330file-like object for your body::331332 with open('massive-body', 'rb') as f:333 requests.post('http://some.url/streamed', data=f)334335.. warning:: It is strongly recommended that you open files in `binary mode`_.336 This is because Requests may attempt to provide the337 ``Content-Length`` header for you, and if it does this value will338 be set to the number of *bytes* in the file. Errors may occur if339 you open the file in *text mode*.340341.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files342343344.. _chunk-encoding:345346Chunk-Encoded Requests347----------------------348349Requests also supports Chunked transfer encoding for outgoing and incoming requests.350To send a chunk-encoded request, simply provide a generator (or any iterator without351a length) for your body::352353 def gen():354 yield 'hi'355 yield 'there'356357 requests.post('http://some.url/chunked', data=gen())358359For chunked encoded responses, it's best to iterate over the data using

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 360why, one step back
360:meth:`Response.iter_content() <requests.Response.iter_content>`. In

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 361why, one step back
361an ideal situation you'll have set ``stream=True`` on the request, in which

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

lines 362–364why, one step back
362case you can iterate chunk-by-chunk by calling ``iter_content`` with a ``chunk_size``
363parameter of ``None``. If you want to set a maximum size of the chunk,364you can set a ``chunk_size`` parameter to any integer.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 365–372why, one step back
365
366367.. _multipart:368369POST Multiple Multipart-Encoded Files370-------------------------------------371372You can send multiple files in one request. For example, suppose you want to

docs cleanupKenneth Reitzbefore adoptione98d71d

line 373why, one step back
373upload image files to an HTML form with a multiple file field 'images'::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 374–376why, one step back
374
375 <input type="file" name="images" multiple="true" required="true"/>376

improve advanced.rstKenneth Reitzbefore adoptionf4445b3

line 377why, one step back
377To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 378–379why, one step back
378
379 >>> url = 'http://httpbin.org/post'

improve advanced.rstKenneth Reitzbefore adoptionf4445b3

lines 380–382why, one step back
380 >>> multiple_files = [
381 ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),382 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 383–450why, one step back
383 >>> r = requests.post(url, files=multiple_files)
384 >>> r.text385 {386 ...387 'files': {'images': 'data:image/png;base64,iVBORw ....'}388 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',389 ...390 }391392.. warning:: It is strongly recommended that you open files in `binary mode`_.393 This is because Requests may attempt to provide the394 ``Content-Length`` header for you, and if it does this value will395 be set to the number of *bytes* in the file. Errors may occur if396 you open the file in *text mode*.397398.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files399400401.. _event-hooks:402403Event Hooks404-----------405406Requests has a hook system that you can use to manipulate portions of407the request process, or signal event handling.408409Available hooks:410411``response``:412 The response generated from a Request.413414415You can assign a hook function on a per-request basis by passing a416``{hook_name: callback_function}`` dictionary to the ``hooks`` request417parameter::418419 hooks=dict(response=print_url)420421That ``callback_function`` will receive a chunk of data as its first422argument.423424::425426 def print_url(r, *args, **kwargs):427 print(r.url)428429If an error occurs while executing your callback, a warning is given.430431If the callback function returns a value, it is assumed that it is to432replace the data that was passed in. If the function doesn't return433anything, nothing else is effected.434435Let's print some request method arguments at runtime::436437 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))438 http://httpbin.org439 <Response [200]>440441.. _custom-auth:442443Custom Authentication444---------------------445446Requests allows you to use specify your own authentication mechanism.447448Any callable which is passed as the ``auth`` argument to a request method will449have the opportunity to modify the request before it is dispatched.450

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 451why, one step back
451Authentication implementations are subclasses of :class:`AuthBase <requests.auth.AuthBase>`,

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 452why, one step back
452and are easy to define. Requests provides two common authentication scheme

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

lines 453–454why, one step back
453implementations in ``requests.auth``: :class:`HTTPBasicAuth <requests.auth.HTTPBasicAuth>` and
454:class:`HTTPDigestAuth <requests.auth.HTTPDigestAuth>`.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 455–483why, one step back
455
456Let's pretend that we have a web service that will only respond if the457``X-Pizza`` header is set to a password value. Unlikely, but just go with it.458459::460461 from requests.auth import AuthBase462463 class PizzaAuth(AuthBase):464 """Attaches HTTP Pizza Authentication to the given Request object."""465 def __init__(self, username):466 # setup any auth-related data here467 self.username = username468469 def __call__(self, r):470 # modify and return the request471 r.headers['X-Pizza'] = self.username472 return r473474Then, we can make a request using our Pizza Auth::475476 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))477 <Response [200]>478479.. _streaming-requests:480481Streaming Requests482------------------483

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 484why, one step back
484With :meth:`Response.iter_lines() <requests.Response.iter_lines>` you can easily

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 485–487why, one step back
485iterate over streaming APIs such as the `Twitter Streaming
486API <https://dev.twitter.com/streaming/overview>`_. Simply487set ``stream`` to ``True`` and iterate over the response with

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 488why, one step back
488:meth:`~requests.Response.iter_lines()`::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 489–498why, one step back
489
490 import json491 import requests492493 r = requests.get('http://httpbin.org/stream/20', stream=True)494495 for line in r.iter_lines():496497 # filter out keep-alive new lines498 if line:

Merge pull request #3678 from nateprewitt/3675_streaming_docsCory Benfieldbefore adoption33bd38b

lines 499–513why, one step back
499 decoded_line = line.decode('utf-8')
500 print(json.loads(decoded_line))501502When using `decode_unicode=True` with503:meth:`Response.iter_lines() <requests.Response.iter_lines>` or504:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want505to provide a fallback encoding in the event the server doesn't provide one::506507 r = requests.get('http://httpbin.org/stream/20', stream=True)508509 if r.encoding is None:510 r.encoding = 'utf-8'511512 for line in r.iter_lines(decode_unicode=True):513 if line:

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 514–517why, one step back
514 print(json.loads(line))
515516.. warning::517

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 518why, one step back
518 :meth:`~requests.Response.iter_lines()` is not reentrant safe.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 519–524why, one step back
519 Calling this method multiple times causes some of the received data
520 being lost. In case you need to call it from multiple places, use521 the resulting iterator object instead::522523 lines = r.iter_lines()524 # Save the first line for later or just skip it

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 525why, one step back
525

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 526why, one step back
526 first_line = next(lines)

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 527why, one step back
527

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 528–541why, one step back
528 for line in lines:
529 print(line)530531.. _proxies:532533Proxies534-------535536If you need to use a proxy, you can configure individual requests with the537``proxies`` argument to any request method::538539 import requests540541 proxies = {

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

lines 542–543why, one step back
542 'http': 'http://10.10.1.10:3128',
543 'https': 'http://10.10.1.10:1080',

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 544–545why, one step back
544 }
545

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 546why, one step back
546 requests.get('http://example.org', proxies=proxies)

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 547–554why, one step back
547
548You can also configure proxies by setting the environment variables549``HTTP_PROXY`` and ``HTTPS_PROXY``.550551::552553 $ export HTTP_PROXY="http://10.10.1.10:3128"554 $ export HTTPS_PROXY="http://10.10.1.10:1080"

docs cleanupKenneth Reitzbefore adoptione98d71d

line 555why, one step back
555

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 556–557why, one step back
556 $ python
557 >>> import requests

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 558why, one step back
558 >>> requests.get('http://example.org')

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 559–561why, one step back
559
560To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::561

improve further advanced.rstKenneth Reitzbefore adoptionf8af499

line 562why, one step back
562 proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 563–569why, one step back
563
564To give a proxy for a specific scheme and host, use the565`scheme://hostname` form for the key. This will match for566any request to the given scheme and exact hostname.567568::569

improve further advanced.rstKenneth Reitzbefore adoptionf8af499

line 570why, one step back
570 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 571–573why, one step back
571
572Note that proxy URLs must include the scheme.573

Merge pull request #3173 from Lukasa/socks-proxy-docsIan Cordascobefore adoption3669b42

lines 574–578why, one step back
574SOCKS
575^^^^^576577.. versionadded:: 2.10.0578

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

line 579why, one step back
579In addition to basic HTTP proxies, Requests also supports proxies using the

Merge pull request #3173 from Lukasa/socks-proxy-docsIan Cordascobefore adoption3669b42

lines 580–596why, one step back
580SOCKS protocol. This is an optional feature that requires that additional
581third-party libraries be installed before use.582583You can get the dependencies for this feature from ``pip``:584585.. code-block:: bash586587 $ pip install requests[socks]588589Once you've installed those dependencies, using a SOCKS proxy is just as easy590as using a HTTP one::591592 proxies = {593 'http': 'socks5://user:pass@host:port',594 'https': 'socks5://user:pass@host:port'595 }596

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 597–657why, one step back
597.. _compliance:
598599Compliance600----------601602Requests is intended to be compliant with all relevant specifications and603RFCs where that compliance will not cause difficulties for users. This604attention to the specification can lead to some behaviour that may seem605unusual to those not familiar with the relevant specification.606607Encodings608^^^^^^^^^609610When you receive a response, Requests makes a guess at the encoding to611use for decoding the response when you access the :attr:`Response.text612<requests.Response.text>` attribute. Requests will first check for an613encoding in the HTTP header, and if none is present, will use `chardet614<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.615616The only time Requests will not do this is if no explicit charset617is present in the HTTP headers **and** the ``Content-Type``618header contains ``text``. In this situation, `RFC 2616619<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies620that the default charset must be ``ISO-8859-1``. Requests follows the621specification in this case. If you require a different encoding, you can622manually set the :attr:`Response.encoding <requests.Response.encoding>`623property, or use the raw :attr:`Response.content <requests.Response.content>`.624625.. _http-verbs:626627HTTP Verbs628----------629630Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,631HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of632using these various verbs in Requests, using the GitHub API.633634We will begin with the verb most commonly used: GET. HTTP GET is an idempotent635method that returns a resource from a given URL. As a result, it is the verb636you ought to use when attempting to retrieve data from a web location. An637example usage would be attempting to get information about a specific commit638from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it639like so::640641 >>> import requests642 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')643644We should confirm that GitHub responded correctly. If it has, we want to work645out what type of content it is. Do this like so::646647 >>> if r.status_code == requests.codes.ok:648 ... print(r.headers['content-type'])649 ...650 application/json; charset=utf-8651652So, GitHub returns JSON. That's great, we can use the :meth:`r.json653<requests.Response.json>` method to parse it into Python objects.654655::656657 >>> commit_data = r.json()

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 658why, one step back
658

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 659–660why, one step back
659 >>> print(commit_data.keys())
660 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 661why, one step back
661

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 662–663why, one step back
662 >>> print(commit_data[u'committer'])
663 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 664why, one step back
664

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 665–695why, one step back
665 >>> print(commit_data[u'message'])
666 makin' history667668So far, so simple. Well, let's investigate the GitHub API a little bit. Now,669we could look at the documentation, but we might have a little more fun if we670use Requests instead. We can take advantage of the Requests OPTIONS verb to671see what kinds of HTTP methods are supported on the url we just used.672673::674675 >>> verbs = requests.options(r.url)676 >>> verbs.status_code677 500678679Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't680actually implement the OPTIONS method. This is an annoying oversight, but it's681OK, we can just use the boring documentation. If GitHub had correctly682implemented OPTIONS, however, they should return the allowed methods in the683headers, e.g.684685::686687 >>> verbs = requests.options('http://a-good-website.com/api/cats')688 >>> print(verbs.headers['allow'])689 GET,HEAD,POST,OPTIONS690691Turning to the documentation, we see that the only other method allowed for692commits is POST, which creates a new commit. As we're using the Requests repo,693we should probably avoid making ham-handed POSTS to it. Instead, let's play694with the Issues feature of GitHub.695

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

lines 696–698why, one step back
696This documentation was added in response to
697`Issue #482 <https://github.com/kennethreitz/requests/issues/482>`_. Given that698this issue already exists, we will use it as an example. Let's start by getting it.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 699–704why, one step back
699
700::701702 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')703 >>> r.status_code704 200

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 705why, one step back
705

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 706why, one step back
706 >>> issue = json.loads(r.text)

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 707why, one step back
707

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 708–709why, one step back
708 >>> print(issue[u'title'])
709 Feature any http verb in docs

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 710why, one step back
710

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 711–720why, one step back
711 >>> print(issue[u'comments'])
712 3713714Cool, we have three comments. Let's take a look at the last of them.715716::717718 >>> r = requests.get(r.url + u'/comments')719 >>> r.status_code720 200

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 721why, one step back
721

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

line 722why, one step back
722 >>> comments = r.json()

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 723why, one step back
723

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 724–725why, one step back
724 >>> print(comments[0].keys())
725 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 726why, one step back
726

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 727–745why, one step back
727 >>> print(comments[2][u'body'])
728 Probably in the "advanced" section729730Well, that seems like a silly place. Let's post a comment telling the poster731that he's silly. Who is the poster, anyway?732733::734735 >>> print(comments[2][u'user'][u'login'])736 kennethreitz737738OK, so let's tell this Kenneth guy that we think this example should go in the739quickstart guide instead. According to the GitHub API doc, the way to do this740is to POST to the thread. Let's do it.741742::743744 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})745 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 746why, one step back
746

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 747–758why, one step back
747 >>> r = requests.post(url=url, data=body)
748 >>> r.status_code749 404750751Huh, that's weird. We probably need to authenticate. That'll be a pain, right?752Wrong. Requests makes it easy to use many forms of authentication, including753the very common Basic Auth.754755::756757 >>> from requests.auth import HTTPBasicAuth758 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 759why, one step back
759

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 760–762why, one step back
760 >>> r = requests.post(url=url, data=body, auth=auth)
761 >>> r.status_code762 201

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 763why, one step back
763

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 764–776why, one step back
764 >>> content = r.json()
765 >>> print(content[u'body'])766 Sounds great! I'll get right on it.767768Brilliant. Oh, wait, no! I meant to add that it would take me a while, because769I had to go feed my cat. If only I could edit this comment! Happily, GitHub770allows us to use another HTTP verb, PATCH, to edit this comment. Let's do771that.772773::774775 >>> print(content[u"id"])776 5804413

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 777why, one step back
777

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 778–779why, one step back
778 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})
779 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

line 780why, one step back
780

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 781–814why, one step back
781 >>> r = requests.patch(url=url, data=body, auth=auth)
782 >>> r.status_code783 200784785Excellent. Now, just to torture this Kenneth guy, I've decided to let him786sweat and not tell him that I'm working on this. That means I want to delete787this comment. GitHub lets us delete comments using the incredibly aptly named788DELETE method. Let's get rid of it.789790::791792 >>> r = requests.delete(url=url, auth=auth)793 >>> r.status_code794 204795 >>> r.headers['status']796 '204 No Content'797798Excellent. All gone. The last thing I want to know is how much of my ratelimit799I've used. Let's find out. GitHub sends that information in the headers, so800rather than download the whole page I'll send a HEAD request to get the801headers.802803::804805 >>> r = requests.head(url=url, auth=auth)806 >>> print(r.headers)807 ...808 'x-ratelimit-remaining': '4995'809 'x-ratelimit-limit': '5000'810 ...811812Excellent. Time to write a Python program that abuses the GitHub API in all813kinds of exciting ways, 4995 more times.814

Merge branch 'TetraEtc-docs-custom-verbs'Cory Benfieldbefore adoptiond0f7a51

lines 815–832why, one step back
815.. _custom-verbs:
816817Custom Verbs818------------819820From time to time you may be working with a server that, for whatever reason,821allows use or even requires use of HTTP verbs not covered above. One example of822this would be the MKCOL method some WEBDAV servers use. Do not fret, these can823still be used with Requests. These make use of the built-in ``.request``824method. For example::825826 >>> r = requests.request('MKCOL', url, data=data)827 >>> r.status_code828 200 # Assuming your call was correct829830Utilising this, you can make use of any method verb that your server allows.831832

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 833–890why, one step back
833.. _link-headers:
834835Link Headers836------------837838Many HTTP APIs feature Link headers. They make APIs more self describing and839discoverable.840841GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_842in their API, for example::843844 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'845 >>> r = requests.head(url=url)846 >>> r.headers['link']847 '<https://api.github.com/users/kennethreitz/repos?page=2&per_page=10>; rel="next", <https://api.github.com/users/kennethreitz/repos?page=6&per_page=10>; rel="last"'848849Requests will automatically parse these link headers and make them easily consumable::850851 >>> r.links["next"]852 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}853854 >>> r.links["last"]855 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}856857.. _transport-adapters:858859Transport Adapters860------------------861862As of v1.0.0, Requests has moved to a modular internal design. Part of the863reason this was done was to implement Transport Adapters, originally864`described here`_. Transport Adapters provide a mechanism to define interaction865methods for an HTTP service. In particular, they allow you to apply per-service866configuration.867868Requests ships with a single Transport Adapter, the :class:`HTTPAdapter869<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests870interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever871a Requests :class:`Session <requests.Session>` is initialized, one of these is872attached to the :class:`Session <requests.Session>` object for HTTP, and one873for HTTPS.874875Requests enables users to create and use their own Transport Adapters that876provide specific functionality. Once created, a Transport Adapter can be877mounted to a Session object, along with an indication of which web services878it should apply to.879880::881882 >>> s = requests.Session()883 >>> s.mount('http://www.github.com', MyAdapter())884885The mount call registers a specific instance of a Transport Adapter to a886prefix. Once mounted, any HTTP request made using that session whose URL starts887with the given prefix will use the given Transport Adapter.888889Many of the details of implementing a Transport Adapter are beyond the scope of890this documentation, but take a look at the next example for a simple SSL use-

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

lines 891–892why, one step back
891case. For more than that, you might look at subclassing the
892:class:`BaseAdapter <requests.adapters.BaseAdapter>`.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 893–903why, one step back
893
894Example: Specific SSL Version895^^^^^^^^^^^^^^^^^^^^^^^^^^^^^896897The Requests team has made a specific choice to use whatever SSL version is898default in the underlying library (`urllib3`_). Normally this is fine, but from899time to time, you might find yourself needing to connect to a service-endpoint900that uses a version that isn't compatible with the default.901902You can use Transport Adapters for this by taking most of the existing903implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

lines 904–905why, one step back
904passed-through to `urllib3`. We'll make a Transport Adapter that instructs the
905library to use SSLv3::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 906–916why, one step back
906
907 import ssl908909 from requests.adapters import HTTPAdapter910 from requests.packages.urllib3.poolmanager import PoolManager911912913 class Ssl3HttpAdapter(HTTPAdapter):914 """"Transport adapter" that allows us to use SSLv3."""915916 def init_poolmanager(self, connections, maxsize, block=False):

cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f

lines 917–919why, one step back
917 self.poolmanager = PoolManager(
918 num_pools=connections, maxsize=maxsize,919 block=block, ssl_version=ssl.PROTOCOL_SSLv3)

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 920–941why, one step back
920
921.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http922.. _`urllib3`: https://github.com/shazow/urllib3923924.. _blocking-or-nonblocking:925926Blocking Or Non-Blocking?927-------------------------928929With the default Transport Adapter in place, Requests does not provide any kind930of non-blocking IO. The :attr:`Response.content <requests.Response.content>`931property will block until the entire response has been downloaded. If932you require more granularity, the streaming features of the library (see933:ref:`streaming-requests`) allow you to retrieve smaller quantities of the934response at a time. However, these calls will still block.935936If you are concerned about the use of blocking IO, there are lots of projects937out there that combine Requests with one of Python's asynchronicity frameworks.938Two excellent examples are `grequests`_ and `requests-futures`_.939940.. _`grequests`: https://github.com/kennethreitz/grequests941.. _`requests-futures`: https://github.com/ross/requests-futures

Document header ordering. (#3295)Cory Benfieldbefore adoption7a404cf

lines 942–945why, one step back
942
943Header Ordering944---------------945

compensate for lack of tasteKenneth Reitzbefore adoption6c9a0ef

line 946why, one step back
946In unusual circumstances you may want to provide headers in an ordered manner. If you pass an ``OrderedDict`` to the ``headers`` keyword argument, that will provide the headers with an ordering. *However*, the ordering of the default headers used by Requests will be preferred, which means that if you override default headers in the ``headers`` keyword argument, they may appear out of order compared to other headers in that keyword argument.

Document header ordering. (#3295)Cory Benfieldbefore adoption7a404cf

line 947why, one step back
947

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 948why, one step back
948If this is problematic, users should consider setting the default headers on a :class:`Session <requests.Session>` object, by setting :attr:`Session <requests.Session.headers>` to a custom ``OrderedDict``. That ordering will always be preferred.

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 949–955why, one step back
949
950.. _timeouts:951952Timeouts953--------954955Most requests to external servers should have a timeout attached, in case the

Merge pull request #3520 from Brausepaul/masterKenneth Reitzbefore adoption33501c7

lines 956–957why, one step back
956server is not responding in a timely manner. By default, requests do not time
957out unless a timeout value is set explicitly. Without a timeout, your code may

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 958–984why, one step back
958hang for minutes or more.
959960The **connect** timeout is the number of seconds Requests will wait for your961client to establish a connection to a remote machine (corresponding to the962`connect()`_) call on the socket. It's a good practice to set connect timeouts963to slightly larger than a multiple of 3, which is the default `TCP packet964retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.965966Once your client has connected to the server and sent the HTTP request, the967**read** timeout is the number of seconds the client will wait for the server968to send a response. (Specifically, it's the number of seconds that the client969will wait *between* bytes sent from the server. In 99.9% of cases, this is the970time before the server sends the first byte).971972If you specify a single value for the timeout, like this::973974 r = requests.get('https://github.com', timeout=5)975976The timeout value will be applied to both the ``connect`` and the ``read``977timeouts. Specify a tuple if you would like to set the values separately::978979 r = requests.get('https://github.com', timeout=(3.05, 27))980981If the remote server is very slow, you can tell Requests to wait forever for982a response, by passing None as a timeout value and then retrieving a cup of983coffee.984

Merge pull request #3513 from nateprewitt/doc_updatesKenneth Reitzbefore adoption786fb19

line 985why, one step back
985::

Merge pull request #2994 from Stranger6667/fix-bad-testCory Benfieldbefore adoption6143b7e

lines 986–989why, one step back
986
987 r = requests.get('https://github.com', timeout=None)988989.. _`connect()`: http://linux.die.net/man/2/connect