Reverted hooks from sub-package to module.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Luca De Vitis · committed by Luca De Vitis · parent d8c923c · Browse files · 6 files·+184 added−203 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+184 added−203 removed
- other:+184 added−203 removed
Provenance
- Commit
07dd324- Tree
cea0646- Author
Luca De Vitis <luca@monkeython.com>- Committer
Luca De Vitis <luca@monkeython.com>- Parent
d8c923c
6 files changed+184 added−203 removed
deleted:requests/hooks/__init__.py-97 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.hooks5-~~~~~~~~~~~~~~6-7-This module provides the capabilities for the Requests hooks system.8-9-Available hooks:10-11-``args``:12- A dictionary of the arguments being sent to Request().13-14-``pre_request``:15- The Request object, directly before being sent.16-17-``post_request``:18- The Request object, directly after being sent.19-20-``response``:21- The response generated from a Request.22-23-"""24-25-import warnings26-from collections import Iterable27-from .. import config28-from . import args29-from . import pre_request30-from . import post_request31-from . import response32-33-def setup_hooks(supplied):34- """Setup the supplied dictionary of hooks.35- Each value is a list of hooks and will extend **default_hooks**.36-37- :param supplied: a dictionary of hooks. Each value can either be a callable38- or a list of callables.39- :type supplied: dict40- :returns: a dictionary of hooks that extends the **default_hooks** dictionary.41- :rtype: dict42- """43-44- # Copy the default hooks settings.45- default = config.settings.default_hooks46- dispatching = dict([(k, v[:]) for k, v in default.items()])47-48- # I abandoned the idea of a dictionary of sets because sets may not keep49- # insertion order, while it may be important. Also, there is no real reason50- # to force hooks to run once.51- for hooks, values in supplied.items():52- hook_list = values if isinstance(values, Iterable) else [values]53- dispatching[hooks].extends(hook_list)54-55- # If header is set, maybe response is encoded. Whatever hook you want to56- # run on response, content decoding should be first.57- if config.settings.base_headers.get('Accept-Encoding', ''):58- dispatching['response'].insert(0, response.decode_encoding)59-60- if config.settings.decode_unicode:61- try:62- # Try unicode encoding just after content decoding...63- index = dispatching['response'].index(response.decode_encoding) + 164- except ValueError:65- # ... Or as first hook66- index = 067- dispatching['response'].insert(index, response.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-97- return datadeleted:requests/hooks/args.py-7 removed
1-"""2-request.hooks.args3-~~~~~~~~~~~~~~~~~~4-5-This module provide a collection of args hooks.6-"""7-deleted:requests/hooks/post_request.py-7 removed
1-"""2-request.hooks.post_request3-~~~~~~~~~~~~~~~~~~~~~~~~~~4-5-This module provide a collection of post_request hooks.6-"""7-deleted:requests/hooks/pre_request.py-7 removed
1-"""2-request.hooks.pre_request3-~~~~~~~~~~~~~~~~~~~~~~~~~4-5-This module provide a collection of pre_request hooks.6-"""7-deleted:requests/hooks/response.py-85 removed
1-"""2-request.hooks.response3-~~~~~~~~~~~~~~~~~~~~~~4-5-This module provide a collection of response hooks.6-"""7-import zlib8-import bz29-from cgi import parse_header10-11-try:12- import json13-except ImportError:14- try:15- import simplejson as json16- except ImportError:17- json = False18-try:19- from lxml import etree20-except ImportError:21- try:22- import xml.etree.cElementTree as etree23- except ImportError:24- try:25- import xml.etree.ElementTree as etree26- except ImportError:27- try:28- import cElementTree as etree29- except ImportError:30- try:31- import elementtree.ElementTree as etree32- except ImportError:33- etree = False34-35-#: Dictionary of content decoders.36-content_decoders = {37- # No decoding applied.38- 'identity': lambda content: content,39- # Decode Response file object compressed with deflate.40- 'deflate': lambda content: zlib.decompress(content),41- # Decode Response file object compressed with gzip.42- 'gzip': lambda content: zlib.decompress(content, 16+zlib.MAX_WBITS),43- # Decode Response file object compressed with bz2.44- # Not a standard Content-Encoding value, but..45- 'bzip2': lambda content: bz2.decompress(content),46-}47-48-# Decode Response file object compressed with compress.49-content_decoders['compress'] = content_decoders['deflate']50-51-def decode_unicode(r):52- """Encode a :py:class:`requests.models.Response` file object in unicode."""53- content_type, params = parse_header(r.headers['content-type'])54- charset = params.get('charset', '').strip("'\"")55- r._content = unicode(r.content, charset) if charset else unicode(r.content)56- return r57-58-def decode_encoding(r):59- """60- Decode a :py:class:`requests.models.Response` content using61- Contetn-Encoding header.62- """63- # Apply decoding only if the header is set.64- encoding = r.headers['content-encoding']65- if encoding:66- r._content = content_decoders[encoding](r.content)67- return r68-69-if json:70- def json_content(r):71- """72- Turns :py:class:`requests.models.Response` content into a dumped73- JSON structure.74- """75- r._content = json.dumps(r.content)76- return r77-78-if etree:79- def etree_content(r):80- """81- Turns :py:class:`requests.models.Response` content into an82- ElementTree structure.83- """84- r._content = etree.fromstring(r.content)85- return radded:requests/hooks.py+184 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.hooks5+~~~~~~~~~~~~~~6+7+This module provides the capabilities for the Requests hooks system.8+9+Available hooks:10+11+``args``:12+ A dictionary of the arguments being sent to Request().13+14+``pre_request``:15+ The Request object, directly before being sent.16+17+``post_request``:18+ The Request object, directly after being sent.19+20+``response``:21+ The response generated from a Request.22+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+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+43+ # Copy the default hooks settings.44+ default = config.settings.default_hooks45+ dispatching = dict([(k, v[:]) for k, v in default.items()])46+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+ """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+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 r