Merge pull request #196 from pyos/patch-2
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix errors introduced by merging an outdated pull request.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents abe33f0, c4f013a · Browse files · 4 files·+18 added−261 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+18 added−261 removed
- other:+18 added−261 removed
Provenance
- Commit
0cfd801- Tree
45b6180- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
abe33f0- Parent 2
c4f013a
4 files changed+18 added−261 removed
modified:requests/api.py+8 added-8 removed
12 unmodified lines13 14 from ._config import get_config15 from .models import Request, Response16 from .status_codes import codes17-from hooks import setup_hooks, dispatch_hooks17+from .hooks import dispatch_hook18 from .utils import cookiejar_from_dict, header_expand19 20 21 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')23 unmodified lines45 46 method = str(method).upper()47 config = get_config(config)48 49- # cookies = cookiejar_from_dict(cookies if cookies is not None else dict())49+ if cookies is None:50+ cookies = {}51+52 # cookies = cookiejar_from_dict(cookies)53 54 # Expand header values55 if headers:15 unmodified lines71 proxies=proxies or config.get('proxies'),72 _pools=_pools73 )74 73- hooks = setup_hooks(hooks if hooks is not None else dict())74-75 # Arguments manipulation hook.76- args = dispatch_hooks(hooks['args'], args)76+ args = dispatch_hook('args', hooks, args)77 78 # Create Request object.79 r = Request(**args)80 81 # Pre-request hook.82- r = dispatch_hooks(hooks['pre_request'], r)82+ r = dispatch_hook('pre_request', hooks, r)83 84 # Only construct the request (for async)85 if _return_request:86 return r2 unmodified lines89 r.send()90 91 # TODO: Add these hooks inline.92 # Post-request hook.93- r = dispatch_hooks(hooks['post_request'], r)93+ r = dispatch_hook('post_request', hooks, r)94 95 # Response manipulation hook.96- r.response = dispatch_hooks(hooks['response'], r.response)96+ r.response = dispatch_hook('response', hooks, r.response)97 98 return r.response99 100 67 unmodified linesdeleted:requests/config.py-80 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.config5-~~~~~~~~~~~~~~~6-7-This module provides the Requests settings feature set.8-9-"""10-11-class Settings(object):12- _singleton = {}13-14- # attributes with defaults15- __attrs__ = []16-17- def __init__(self, **kwargs):18- super(Settings, self).__init__()19-20- self.__dict__ = self._singleton21-22-23- def __call__(self, *args, **kwargs):24- # new instance of class to call25- r = self.__class__()26-27- # cache previous settings for __exit__28- r.__cache = self.__dict__.copy()29- map(self.__cache.setdefault, self.__attrs__)30-31- # set new settings32- self.__dict__.update(*args, **kwargs)33-34- return r35-36-37- def __enter__(self):38- pass39-40-41- def __exit__(self, *args):42-43- # restore cached copy44- self.__dict__.update(self.__cache.copy())45- del self.__cache46-47-48- def __getattribute__(self, key):49- if key in object.__getattribute__(self, '__attrs__'):50- try:51- return object.__getattribute__(self, key)52- except AttributeError:53- return None54- return object.__getattribute__(self, key)55-56-57-settings = Settings()58-59-settings.base_headers = {60- 'User-Agent': 'python-requests.org',61- 'Accept-Encoding': ', '.join([ 'identity', 'deflate', 'compress', 'gzip' ]),62-}63-settings.accept_gzip = True64-settings.proxies = None65-settings.verbose = None66-settings.timeout = None67-settings.max_redirects = 3068-settings.decode_unicode = False69-settings.gracefull_hooks = True70-71-#: A dictionary of default hooks to be applied, based on settings.72-settings.default_hooks = {73- 'args': list(),74- 'pre_request': list(),75- 'post_request': list(),76- 'response': list()77-}78-79-#: Use socket.setdefaulttimeout() as fallback?80-settings.timeout_fallback = Truemodified:requests/hooks.py+7 added-150 removed
21 unmodified lines22 23 """24 25 import warnings26-from collections import Iterable27-import config28-import zlib29-import bz230-from cgi import parse_header26+import collections27 32-def setup_hooks(supplied):33- """Setup a hooks mapping, based on the supplied argument. Eache mapping34- value will be list of hooks that will extend the **default_hooks**.28 36- :param supplied: a dictionary of hooks. Each value can either be a callable37- or a list of callables.38- :type supplied: dict39- :returns: a dictionary of hooks that extends the **default_hooks** dictionary.40- :rtype: dict41- """29+def dispatch_hook(key, hooks, hook_data):30+ """Dipatches a hook dictionary on a given peice of data."""31 43- # Copy the default hooks settings.44- default = config.settings.default_hooks45- dispatching = dict([(k, v[:]) for k, v in default.items()])32+ hooks = (hooks or {}).get(key, [])33+ hooks = hooks if isinstance(hooks, collections.Iterable) else [hooks]34 47- # I abandoned the idea of a dictionary of sets because sets may not keep48- # insertion order, while it may be important. Also, there is no real reason49- # to force hooks to run once.50- for hooks, values in supplied.items():51- hook_list = values if isinstance(values, Iterable) else [values]52- dispatching[hooks].extend(hook_list)53-54- # If header is set by config, maybe response is encoded.55- if config.settings.base_headers.get('Accept-Encoding', ''):56- if not decode_encoding in dispatching['response']:57- # It's safer to put decoding as first hook.58- dispatching['response'].insert(0, decode_encoding)59-60- if config.settings.decode_unicode:61- try:62- # Try unicode encoding just after content decoding...63- index = dispatching['response'].index(decode_encoding) + 164- except ValueError:65- # ... Or as first hook66- index = 067- dispatching['response'].insert(index, decode_unicode)68-69- return dispatching70-71-def dispatch_hooks(hooks, data):72- """Dispatches multiple hooks on a given piece of data.73-74- :param key: the hooks group to lookup75- :type key: str76- :param hooks: the hooks dictionary. The value of each key can be a callable77- object, or a list of callable objects.78- :type hooks: dict79- :param data: the object on witch the hooks should be applied80- :type data: object81- """35 for hook in hooks:36 try:84- # hook must be a callable.85- data = hook(data)86-37+ hook_data = hook(hook_data) or hook_data38 except Exception, why:88-89- # Letting users to choose a policy may be an idea. It can be as90- # simple as "be gracefull, or not":91- #92- # config.settings.gracefull_hooks = True | False93- if not config.settings.gracefull_hooks: raise94-39 warnings.warn(str(why))40 97- return data98-99-#: Example response hook that turns a JSON formatted100-#: :py:class:`requests.models.Response.content` into a dumped data structure::101-#:102-#: try:103-#: import json104-#: except ImportError:105-#: try:106-#: import simplejson as json107-#: except ImportError:108-#: json = False109-#:110-#: if json:111-#: def json_content(r):112-#: """Turns content into a dumped JSON structure."""113-#: r._content = json.dumps(r.content)114-#: return r115-#:116-#: Example response hook that turns an XML formatted117-#: :py:class:`requests.models.Response.content` into an ElementTree::118-#:119-#: try:120-#: from lxml import etree121-#: except ImportError:122-#: try:123-#: import xml.etree.cElementTree as etree124-#: except ImportError:125-#: try:126-#: import xml.etree.ElementTree as etree127-#: except ImportError:128-#: try:129-#: import cElementTree as etree130-#: except ImportError:131-#: try:132-#: import elementtree.ElementTree as etree133-#: except ImportError:134-#: etree = False135-#:136-#: if etree:137-#: def etree_content(r):138-#: """Turns content into an ElementTree structure."""139-#: r._content = etree.fromstring(r.content)140-#: return r141-142-def decode_unicode(r):143- """Encode content into unicode string.144-145- :param r: response object146- :type r: :py:class:`requests.models.Response`147- :returns: the same input object.148- :rtype: :py:class:`requests.models.Response`149- """150- content_type, params = parse_header(r.headers['content-type'])151- charset = params.get('charset', '').strip("'\"")152- r._content = unicode(r.content, charset) if charset else unicode(r.content)153- return r154-155-def decode_encoding(r):156- """Decode content using Contetn-Encoding header.157-158- :param r: response object159- :type r: :py:class:`requests.models.Response`160- :returns: the same input object.161- :rtype: :py:class:`requests.models.Response`162- """163-164- # Dictionary of content decoders.165- decode = {166- # No decoding applied.167- 'identity': lambda content: content,168- # Decode Response content compressed with deflate.169- 'deflate': lambda content: zlib.decompress(content),170- # Decode Response content compressed with gzip.171- 'gzip': lambda content: zlib.decompress(content, 16+zlib.MAX_WBITS),172- # Decode Response content compressed with bz2.173- # Not a standard Content-Encoding value, but..174- 'bzip2': lambda content: bz2.decompress(content),175- }176- # Decode Response content compressed with compress.177- # If I understood zlib...178- decode['compress'] = decode['deflate']179-180- # Apply decoding only if the header is set.181- encoding = r.headers['content-encoding']182- if encoding:183- r._content = decode[encoding](r.content)184- return r41+ return hook_datamodified:requests/models.py+3 added-23 removed
451 unmodified lines452 """Content of the response, in bytes or unicode453 (if available).454 """455 456- if self._content is None:457- # Read the contents.458- self._content = self.fo.read()456+ if self._content is not None:457+ return self._content458 459 if self._content_consumed:460 raise RuntimeError(461 'The content for this response was already consumed')463- # # Decode GZip'd content.464- # if 'gzip' in self.headers.get('content-encoding', ''):465- # try:466- # self._content = decode_gzip(self._content)467- # except zlib.error:468- # pass462 470- self._content = self.fo.read()463+ # Read the contents.464 self._content = self.raw.read() or self.raw.data465 466 # Decode GZip'd content.467 if 'gzip' in self.headers.get('content-encoding', ''):2 unmodified lines470 except zlib.error:471 pass472 473 # Decode unicode content.481- if settings.decode_unicode:482- self._content = get_unicode_from_response(self)483- # Decode GZip'd content.484- if 'gzip' in self.headers.get('content-encoding', ''):485- try:486- self._content = decode_gzip(self._content)487- except zlib.error:488- pass489-490- # Decode unicode content.474 if self.config.get('decode_unicode'):475 self._content = get_unicode_from_response(self)493- # # Decode unicode content.494- # if settings.decode_unicode:495- # self._content = get_unicode_from_response(self)476 477 self._content_consumed = True478 return self._content479 17 unmodified lines