Skip to content
Myr

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

4 files+17 added−91 removed

modified:docs/user/advanced.rst+9 added-77 removed
114 unmodified lines
115116Body Content Workflow117---------------------118119By 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::119By 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::120121 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)123124At this point only the response headers have been downloaded and the connection remains open, hence allowing us to make content retrieval conditional::125126 if int(r.headers['content-length']) < TOO_LONG:
1 unmodified line
128 ...129130You 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`.131132Note that in versions prior to 0.13.6 the ``prefetch`` default was set to ``False``.133132Configuring Requests133--------------------134135Sometimes you may want to configure a request to customize its behavior. To do
4 unmodified lines
140----------141142Excellent 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!143146Note 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.144Note 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.145148If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::146150 s = requests.session()151 s.config['keep_alive'] = False152153154Asynchronous Requests155----------------------156157158``requests.async`` has been removed from requests and is now its own repository named `GRequests <https://github.com/kennethreitz/grequests>`_.159160147Event Hooks148-----------149150Requests has a hook system that you can use to manipulate portions of151the request process, or signal event handling.152153Available hooks:154169``args``:170 A dictionary of the arguments being sent to Request().171172``pre_request``:173 The Request object, directly before being sent.174175``post_request``:176 The Request object, directly after being sent.177155``response``:156 The response generated from a Request.157158159You can assign a hook function on a per-request basis by passing a160``{hook_name: callback_function}`` dictionary to the ``hooks`` request161parameter::162186 hooks=dict(args=print_url)163 hooks=dict(response=print_url)164165That ``callback_function`` will receive a chunk of data as its first166argument.167168::169193 def print_url(args):194 print args['url']170 def print_url(r):171 print(r.url)172173If an error occurs while executing your callback, a warning is given.174175If the callback function returns a value, it is assumed that it is to
1 unmodified line
177anything, nothing else is effected.178179Let's print some request method arguments at runtime::180204 >>> 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]>184208Let's hijack some arguments this time with a new callback::185210 def hack_headers(args):211 if args.get('headers') is None:212 args['headers'] = dict()213214 args['headers'].update({'X-Testing': 'True'})215216 return args217218 hooks = dict(args=hack_headers)219 headers = dict(yo=dawg)220221And give it a try::222223 >>> 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 }238239186Custom Authentication187---------------------188189Requests allows you to use specify your own authentication mechanism.
38 unmodified lines
228 import requests229 import json230231 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)233234 for line in r.iter_lines():235 if line: # filter out keep-alive new lines236 print json.loads(line)237238293Verbose Logging294---------------295296If you want to get a good look at what HTTP requests are being sent297by your application, you can turn on verbose logging.298299To do so, just configure Requests with a stream to write to::300301 >>> 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]>305306239Proxies240-------241242If you need to use a proxy, you can configure individual requests with the
37 unmodified lines
280281When you receive a response, Requests makes a guess at the encoding to use for282decoding the response when you call the ``Response.text`` method. Requests283will first check for an encoding in the HTTP header, and if none is present,352will use `chardet <http://pypi.python.org/pypi/chardet>`_ to attempt to guess284will use `charade <http://pypi.python.org/pypi/charade>`_ to attempt to guess285the encoding.286287The only time Requests will not do this is if no explicit charset is present288in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In
205 unmodified lines
modified:docs/user/quickstart.rst+2 added-2 removed
137 unmodified lines
138--------------------139140In the rare case that you'd like to get the raw socket response from the141server, 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::143144 >>> 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 lines
modified:requests/models.py+2 added-9 removed
526 unmodified lines
527 content = str(self.content, errors='replace')528529 return content530531 @property531 def json(self):532 """Returns the json-encoded content of a response, if any."""533534 if not self.encoding and len(self.content) > 3:
2 unmodified lines
537 # 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)543544 @property545 def links(self):546 """Returns the parsed header links of the response, if any."""
33 unmodified lines
modified:requests/sessions.py+4 added-3 removed
60 unmodified lines
616263class SessionRedirectMixin(object):6465 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."""6768 i = 069
54 unmodified lines
124 allow_redirects=False,125 stream=stream,126 timeout=timeout,127 verify=verify,128 cert=cert128 cert=cert,129 proxies=proxies130 )131132 i += 1133 yield resp
121 unmodified lines
255 # Send the request.256 resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)257258 # 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)260261 # Resolve redirects if allowed.262 history = [r for r in gen] if allow_redirects else []263
112 unmodified lines