Merge branch 'develop' of https://github.com/monkeython/requests into develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conflicts: requests/api.py requests/config.py requests/models.py
authored by Kenneth Reitz · committed by Kenneth Reitz · parents f524fe4, 07dd324 · Browse files · 4 files·+263 added−16 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+263 added−16 removed
- other:+263 added−16 removed
Provenance
- Commit
e4c85b3- Tree
41504ea- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
f524fe4- Parent 2
07dd324
4 files changed+263 added−16 removed
modified:requests/api.py+10 added-7 removed
12 unmodified lines13 14 from ._config import get_config15 from .models import Request, Response16 from .status_codes import codes17-from .hooks import dispatch_hook17+from hooks import setup_hooks, dispatch_hooks18 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- if cookies is None:50- cookies = {}49+ cookies = cookiejar_from_dict(cookies if cookies is not None else dict())50 51+ cookies = cookiejar_from_dict(cookies)52+53 # cookies = cookiejar_from_dict(cookies)54 55 # Expand header values56 if headers:14 unmodified lines71 allow_redirects=allow_redirects,72 proxies=proxies or config.get('proxies'),73 _pools=_pools74 )75+ 76+ hooks = setup_hooks(hooks if hooks is not None else dict())77 78 # Arguments manipulation hook.76- args = dispatch_hook('args', hooks, args)79+ args = dispatch_hooks(hooks['args'], args)80 81 # Create Request object.82 r = Request(**args)83 84 # Pre-request hook.82- r = dispatch_hook('pre_request', hooks, r)85+ r = dispatch_hooks(hooks['pre_request'], r)86 87 # Only construct the request (for async)88 if _return_request:89 return r2 unmodified lines92 r.send()93 94 # TODO: Add these hooks inline.95 # Post-request hook.93- r = dispatch_hook('post_request', hooks, r)96+ r = dispatch_hooks(hooks['post_request'], r)97 98 # Response manipulation hook.96- r.response = dispatch_hook('response', hooks, r.response)99+ r.response = dispatch_hooks(hooks['response'], r.response)100 101 return r.response102 103 67 unmodified linesadded:requests/config.py+80 added
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+150 added-6 removed
21 unmodified lines22 23 """24 25 import warnings26+from collections import Iterable27+import config28+import zlib29+import bz230+from cgi import parse_header31 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**.35 28-def dispatch_hook(key, hooks, hook_data):29- """Dipatches a hook dictionary on a given peice of data."""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+ """42 31- hooks = hooks or dict()43+ # Copy the default hooks settings.44+ default = config.settings.default_hooks45+ dispatching = dict([(k, v[:]) for k, v in default.items()])46 33- if key in hooks: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:35- return hooks.get(key).__call__(hook_data) or hook_data62+ # 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+ """82+ for hook in hooks:83+ try:84+ # hook must be a callable.85+ data = hook(data)86+87 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+95 warnings.warn(str(why))96 40- return hook_data97+ 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 rmodified:requests/models.py+23 added-3 removed
450 unmodified lines451 """Content of the response, in bytes or unicode452 (if available).453 """454 455- if self._content is not None:456- return self._content455+ if self._content is None:456+ # Read the contents.457+ self._content = self.fo.read()458 459 if self._content_consumed:460 raise RuntimeError(461 'The content for this response was already consumed')462+ # # Decode GZip'd content.463+ # if 'gzip' in self.headers.get('content-encoding', ''):464+ # try:465+ # self._content = decode_gzip(self._content)466+ # except zlib.error:467+ # pass468 462- # Read the contents.469+ self._content = self.fo.read()470 self._content = self.raw.read() or self.raw.data471 472 # Decode GZip'd content.473 if 'gzip' in self.headers.get('content-encoding', ''):2 unmodified lines476 except zlib.error:477 pass478 479 # Decode unicode content.480+ if settings.decode_unicode:481+ self._content = get_unicode_from_response(self)482+ # Decode GZip'd content.483+ if 'gzip' in self.headers.get('content-encoding', ''):484+ try:485+ self._content = decode_gzip(self._content)486+ except zlib.error:487+ pass488+489+ # Decode unicode content.490 if self.config.get('decode_unicode'):491 self._content = get_unicode_from_response(self)492+ # # Decode unicode content.493+ # if settings.decode_unicode:494+ # self._content = get_unicode_from_response(self)495 496 self._content_consumed = True497 return self._content498 17 unmodified lines