Coverage for requests.models : 55%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: utf-8 -*-
requests.models ~~~~~~~~~~~~~~~
This module contains the primary objects that power Requests. """
HTTPError, RequestException, MissingSchema, InvalidURL, ChunkedEncodingError, ContentDecodingError) guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, iter_slices, guess_json_utf, super_len, to_native_string) cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO, is_py2, chardet, json, builtin_str, basestring, IncompleteRead)
#: The set of HTTP status codes that indicate an automatically #: processable redirect. codes.moved, # 301 codes.found, # 302 codes.other, # 303 codes.temporary_moved, # 307 )
def path_url(self): """Build the path URL to use."""
path = '/'
def _encode_params(data): """Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """
return data return data (k.encode('utf-8') if isinstance(k, str) else k, v.encode('utf-8') if isinstance(v, str) else v)) else: return data
def _encode_files(files, data): """Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict.
""" if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.")
new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {})
for field, val in fields: if isinstance(val, basestring) or not hasattr(val, '__iter__'): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v)
new_fields.append( (field.decode('utf-8') if isinstance(field, bytes) else field, v.encode('utf-8') if isinstance(v, str) else v))
for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, str): fp = StringIO(fp) if isinstance(fp, bytes): fp = BytesIO(fp)
rf = RequestField(name=k, data=fp.read(), filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf)
body, content_type = encode_multipart_formdata(new_fields)
return body, content_type
"""Properly register a hook."""
raise ValueError('Unsupported event specified, with event name "%s"' % (event))
self.hooks[event].append(hook)
"""Deregister a previously registered hook. Returns True if the hook existed, False if not. """
try: self.hooks[event].remove(hook) return True except ValueError: return False
"""A user-created :class:`Request <Request>` object.
Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
:param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach the request. If a dictionary is provided, form-encoding will take place. :param params: dictionary of URL parameters to append to the URL. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage.
Usage::
>>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]>
""" method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None):
# Default empty dicts for dict params.
self.register_hook(event=k, hook=v)
return '<Request [%s]>' % (self.method)
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p
"""The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server.
Generated from either a :class:`Request <Request>` object or manually.
Usage::
>>> import requests >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> r = req.prepare() <PreparedRequest [GET]>
>>> s = requests.Session() >>> s.send(r) <Response [200]>
"""
#: HTTP verb to send to the server. #: HTTP URL to send the request to. #: dictionary of HTTP headers. # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called #: request body to send to the server. #: dictionary of callback hooks, for internal usage.
data=None, params=None, auth=None, cookies=None, hooks=None): """Prepares the entire request with the given parameters."""
# Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
return '<PreparedRequest [%s]>' % (self.method)
p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() p._cookies = self._cookies.copy() p.body = self.body p.hooks = self.hooks return p
"""Prepares the given HTTP method."""
"""Prepares the given HTTP URL.""" #: Accept objects that have string representations. except NameError: # We're on Python 3. url = str(url) except UnicodeDecodeError: pass
# Don't do any URL preparation for oddball schemes self.url = url return
# Support for unicode domain names and paths.
raise MissingSchema("Invalid URL {0!r}: No schema supplied. " "Perhaps you meant http://{0}?".format(url))
raise InvalidURL("Invalid URL %r: No host supplied" % url)
# Only want to apply IDNA to the hostname except UnicodeError: raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location netloc += '@' netloc += ':' + str(port)
# Bare domains aren't valid URLs. path = '/'
query = query.encode('utf-8') fragment = fragment.encode('utf-8')
query = '%s&%s' % (query, enc_params) else:
"""Prepares the given HTTP headers."""
else: self.headers = CaseInsensitiveDict()
"""Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator. # If not, run through normal process.
# Nottin' on you.
hasattr(data, '__iter__'), not isinstance(data, (basestring, list, tuple, dict)) ])
except (TypeError, AttributeError, UnsupportedOperation): length = None
body = data
if files: raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
if length is not None: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: # Multi-part file uploads. (body, content_type) = self._encode_files(files, data) else: body = self._encode_params(data) if isinstance(data, str) or isinstance(data, builtin_str) or hasattr(data, 'read'): content_type = None else: content_type = 'application/x-www-form-urlencoded'
# Add content-type if it wasn't explicitly provided. self.headers['Content-Type'] = content_type
body.seek(0, 2) self.headers['Content-Length'] = builtin_str(body.tell()) body.seek(0, 0) l = super_len(body) if l: self.headers['Content-Length'] = builtin_str(l) self.headers['Content-Length'] = '0'
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes. r = auth(self)
# Update self to reflect the auth changes. self.__dict__.update(r.__dict__)
# Recompute Content-Length self.prepare_content_length(self.body)
"""Prepares the given HTTP cookie data."""
else: self._cookies = cookiejar_from_dict(cookies)
self.headers['Cookie'] = cookie_header
"""Prepares the given hooks."""
"""The :class:`Response <Response>` object, which contains a server's response to an HTTP request. """
'_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request', ]
#: Integer Code of responded HTTP Status, e.g. 404 or 200.
#: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header.
#: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. # This requirement does not apply for use internally to Requests.
#: Final URL location of Response.
#: Encoding to decode with when accessing r.text.
#: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request.
#: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
#: A CookieJar of Cookies the server sent back.
#: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta)
# Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content
return dict( (attr, getattr(self, attr, None)) for attr in self.__attrs__ )
for name, value in state.items(): setattr(self, name, value)
# pickled objects do not have .raw setattr(self, '_content_consumed', True) setattr(self, 'raw', None)
return '<Response [%s]>' % (self.status_code)
"""Returns true if :attr:`status_code` is 'OK'.""" return self.ok
"""Returns true if :attr:`status_code` is 'OK'.""" return self.ok
"""Allows you to use a response as an iterator.""" return self.iter_content(128)
def ok(self): try: self.raise_for_status() except RequestException: return False return True
def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """
def apparent_encoding(self): """The apparent encoding, provided by the chardet library""" return chardet.detect(self.content)['encoding']
"""Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ # Special case for urllib3. except IncompleteRead as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except AttributeError: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk
# simulate reading small chunks of the content
chunks = stream_decode_response_unicode(chunks, self)
"""Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. """
pending = None
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
if pending is not None: chunk = pending + chunk lines = chunk.splitlines()
if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None
for line in lines: yield line
if pending is not None: yield pending
def content(self): """Content of the response, in bytes."""
# Read the contents. raise RuntimeError( 'The content for this response was already consumed')
self._content = None else:
except AttributeError: self._content = None
# don't need to release the connection; that's been handled by urllib3 # since we exhausted the data.
def text(self): """Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using ``chardet``.
The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """
# Try charset from content-type
return str('')
# Fallback to auto-detected encoding. encoding = self.apparent_encoding
# Decode unicode from given encoding. except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors='replace')
"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes. """
if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return json.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return json.loads(self.text, **kwargs)
def links(self): """Returns the parsed header links of the response, if any."""
header = self.headers.get('link')
# l = MultiDict() l = {}
if header: links = parse_header_links(header)
for link in links: key = link.get('rel') or link.get('url') l[key] = link
return l
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
elif 500 <= self.status_code < 600: http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)
if http_error_msg: raise HTTPError(http_error_msg, response=self)
"""Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.* """ return self.raw.release_conn() |