update docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 480a382 · Browse files · 4 files·+17 added−91 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+17 added−91 removed
- other:+17 added−91 removed
Provenance
- Commit
1451ba0- Tree
99ec319- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
480a382
4 files changed+17 added−91 removed
modified:docs/user/advanced.rst+9 added-77 removed
114 unmodified lines115 116 Body Content Workflow117 ---------------------118 119-By default, when you make a request, the body of the response is downloaded immediately. You can override this behavior and defer downloading the response body until you access the :class:`Response.content` attribute with the ``prefetch`` parameter::119+By default, when you make a request, the body of the response is downloaded immediately. You can override this behavior and defer downloading the response body until you access the :class:`Response.content` attribute with the ``stream`` parameter::120 121 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'122- r = requests.get(tarball_url, prefetch=False)122+ r = requests.get(tarball_url, stream=True)123 124 At this point only the response headers have been downloaded and the connection remains open, hence allowing us to make content retrieval conditional::125 126 if int(r.headers['content-length']) < TOO_LONG:1 unmodified line128 ...129 130 You can further control the workflow by use of the :class:`Response.iter_content` and :class:`Response.iter_lines` methods, or reading from the underlying urllib3 :class:`urllib3.HTTPResponse` at :class:`Response.raw`.131 132-Note that in versions prior to 0.13.6 the ``prefetch`` default was set to ``False``.133-132 Configuring Requests133 --------------------134 135 Sometimes you may want to configure a request to customize its behavior. To do4 unmodified lines140 ----------141 142 Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!143 146-Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set ``prefetch`` to ``True`` or read the ``content`` property of the ``Response`` object.144+Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set ``stream`` to ``False`` or read the ``content`` property of the ``Response`` object.145 148-If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::146 150- s = requests.session()151- s.config['keep_alive'] = False152-153-154-Asynchronous Requests155-----------------------156-157-158-``requests.async`` has been removed from requests and is now its own repository named `GRequests <https://github.com/kennethreitz/grequests>`_.159-160-147 Event Hooks148 -----------149 150 Requests has a hook system that you can use to manipulate portions of151 the request process, or signal event handling.152 153 Available hooks:154 169-``args``:170- A dictionary of the arguments being sent to Request().171-172-``pre_request``:173- The Request object, directly before being sent.174-175-``post_request``:176- The Request object, directly after being sent.177-155 ``response``:156 The response generated from a Request.157 158 159 You can assign a hook function on a per-request basis by passing a160 ``{hook_name: callback_function}`` dictionary to the ``hooks`` request161 parameter::162 186- hooks=dict(args=print_url)163+ hooks=dict(response=print_url)164 165 That ``callback_function`` will receive a chunk of data as its first166 argument.167 168 ::169 193- def print_url(args):194- print args['url']170+ def print_url(r):171+ print(r.url)172 173 If an error occurs while executing your callback, a warning is given.174 175 If the callback function returns a value, it is assumed that it is to1 unmodified line177 anything, nothing else is effected.178 179 Let's print some request method arguments at runtime::180 204- >>> requests.get('http://httpbin.org', hooks=dict(args=print_url))181+ >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))182 http://httpbin.org183 <Response [200]>184 208-Let's hijack some arguments this time with a new callback::185 210- def hack_headers(args):211- if args.get('headers') is None:212- args['headers'] = dict()213-214- args['headers'].update({'X-Testing': 'True'})215-216- return args217-218- hooks = dict(args=hack_headers)219- headers = dict(yo=dawg)220-221-And give it a try::222-223- >>> requests.get('http://httpbin.org/headers', hooks=hooks, headers=headers)224- {225- "headers": {226- "Content-Length": "",227- "Accept-Encoding": "gzip",228- "Yo": "dawg",229- "X-Forwarded-For": "::ffff:24.127.96.129",230- "Connection": "close",231- "User-Agent": "python-requests.org",232- "Host": "httpbin.org",233- "X-Testing": "True",234- "X-Forwarded-Protocol": "",235- "Content-Type": ""236- }237- }238-239-186 Custom Authentication187 ---------------------188 189 Requests allows you to use specify your own authentication mechanism.38 unmodified lines228 import requests229 import json230 231 r = requests.post('https://stream.twitter.com/1/statuses/filter.json',286- data={'track': 'requests'}, auth=('username', 'password'), prefetch=False)232+ data={'track': 'requests'}, auth=('username', 'password'), stream=True)233 234 for line in r.iter_lines():235 if line: # filter out keep-alive new lines236 print json.loads(line)237 238 293-Verbose Logging294----------------295-296-If you want to get a good look at what HTTP requests are being sent297-by your application, you can turn on verbose logging.298-299-To do so, just configure Requests with a stream to write to::300-301- >>> my_config = {'verbose': sys.stderr}302- >>> requests.get('http://httpbin.org/headers', config=my_config)303- 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers304- <Response [200]>305-306-239 Proxies240 -------241 242 If you need to use a proxy, you can configure individual requests with the37 unmodified lines280 281 When you receive a response, Requests makes a guess at the encoding to use for282 decoding the response when you call the ``Response.text`` method. Requests283 will first check for an encoding in the HTTP header, and if none is present,352-will use `chardet <http://pypi.python.org/pypi/chardet>`_ to attempt to guess284+will use `charade <http://pypi.python.org/pypi/charade>`_ to attempt to guess285 the encoding.286 287 The only time Requests will not do this is if no explicit charset is present288 in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In205 unmodified linesmodified:docs/user/quickstart.rst+2 added-2 removed
137 unmodified lines138 --------------------139 140 In the rare case that you'd like to get the raw socket response from the141 server, you can access ``r.raw``. If you want to do this, make sure you set142-``prefetch=False`` in your initial request. Once you do, you can do this::142+``stream=True`` in your initial request. Once you do, you can do this::143 144- >>> r = requests.get('https:/github.com/timeline.json', prefetch=False)144+ >>> r = requests.get('https:/github.com/timeline.json', stream=True)145 >>> r.raw146 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>147 >>> r.raw.read(10)148 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'347 unmodified linesmodified:requests/models.py+2 added-9 removed
526 unmodified lines527 content = str(self.content, errors='replace')528 529 return content530 531- @property531 def json(self):532 """Returns the json-encoded content of a response, if any."""533 534 if not self.encoding and len(self.content) > 3:2 unmodified lines537 # decoding fails, fall back to `self.text` (using chardet to make538 # a best guess).539 encoding = guess_json_utf(self.content)540 if encoding is not None:542- try:543- return json.loads(self.content.decode(encoding))544- except (ValueError, UnicodeDecodeError):545- pass546- try:547- return json.loads(self.text or self.content)548- except ValueError:549- return None541+ return json.loads(self.content.decode(encoding))542+ return json.loads(self.text or self.content)543 544 @property545 def links(self):546 """Returns the parsed header links of the response, if any."""33 unmodified linesmodified:requests/sessions.py+4 added-3 removed
60 unmodified lines61 62 63 class SessionRedirectMixin(object):64 65- def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None):65+ def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None):66 """Receives a Response. Returns a generator of Responses."""67 68 i = 069 54 unmodified lines124 allow_redirects=False,125 stream=stream,126 timeout=timeout,127 verify=verify,128- cert=cert128+ cert=cert,129+ proxies=proxies130 )131 132 i += 1133 yield resp121 unmodified lines255 # Send the request.256 resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)257 258 # Redirect resolving generator.258- gen = self.resolve_redirects(resp, req, stream, timeout, verify, cert)259+ gen = self.resolve_redirects(resp, req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)260 261 # Resolve redirects if allowed.262 history = [r for r in gen] if allow_redirects else []263 112 unmodified lines