Skip to content
Myr

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

6 files+184 added−203 removed

deleted:requests/hooks/__init__.py-97 removed
1# -*- coding: utf-8 -*-23"""4requests.hooks5~~~~~~~~~~~~~~67This module provides the capabilities for the Requests hooks system.89Available hooks:1011``args``:12 A dictionary of the arguments being sent to Request().1314``pre_request``:15 The Request object, directly before being sent.1617``post_request``:18 The Request object, directly after being sent.1920``response``:21 The response generated from a Request.2223"""2425import warnings26from collections import Iterable27from .. import config28from . import args29from . import pre_request30from . import post_request31from . import response3233def setup_hooks(supplied):34 """Setup the supplied dictionary of hooks.35 Each value is a list of hooks and will extend **default_hooks**.3637 :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 """4344 # Copy the default hooks settings.45 default = config.settings.default_hooks46 dispatching = dict([(k, v[:]) for k, v in default.items()])4748 # 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)5455 # 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)5960 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)6869 return dispatching7071def dispatch_hooks(hooks, data):72 """Dispatches multiple hooks on a given piece of data.7374 :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)8687 except Exception, why:8889 # 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: raise9495 warnings.warn(str(why))9697 return data
deleted:requests/hooks/args.py-7 removed
1"""2request.hooks.args3~~~~~~~~~~~~~~~~~~45This module provide a collection of args hooks.6"""7
deleted:requests/hooks/post_request.py-7 removed
1"""2request.hooks.post_request3~~~~~~~~~~~~~~~~~~~~~~~~~~45This module provide a collection of post_request hooks.6"""7
deleted:requests/hooks/pre_request.py-7 removed
1"""2request.hooks.pre_request3~~~~~~~~~~~~~~~~~~~~~~~~~45This module provide a collection of pre_request hooks.6"""7
deleted:requests/hooks/response.py-85 removed
1"""2request.hooks.response3~~~~~~~~~~~~~~~~~~~~~~45This module provide a collection of response hooks.6"""7import zlib8import bz29from cgi import parse_header1011try:12 import json13except ImportError:14 try:15 import simplejson as json16 except ImportError:17 json = False18try:19 from lxml import etree20except 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 = False3435#: Dictionary of content decoders.36content_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}4748# Decode Response file object compressed with compress.49content_decoders['compress'] = content_decoders['deflate']5051def 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 r5758def 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 r6869if 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 r7778if 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 r
added:requests/hooks.py+184 added
1# -*- coding: utf-8 -*-23"""4requests.hooks5~~~~~~~~~~~~~~67This module provides the capabilities for the Requests hooks system.89Available hooks:1011``args``:12 A dictionary of the arguments being sent to Request().1314``pre_request``:15 The Request object, directly before being sent.1617``post_request``:18 The Request object, directly after being sent.1920``response``:21 The response generated from a Request.2223"""2425import warnings26from collections import Iterable27import config28import zlib29import bz230from cgi import parse_header3132def 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**.3536 :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 """4243 # Copy the default hooks settings.44 default = config.settings.default_hooks45 dispatching = dict([(k, v[:]) for k, v in default.items()])4647 # 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)5354 # 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)5960 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)6869 return dispatching7071def dispatch_hooks(hooks, data):72 """Dispatches multiple hooks on a given piece of data.7374 :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)8687 except Exception, why:8889 # 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: raise9495 warnings.warn(str(why))9697 return data9899#: 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 r141142def decode_unicode(r):143 """Encode content into unicode string.144145 :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 r154155def decode_encoding(r):156 """Decode content using Contetn-Encoding header.157158 :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 """163164 # 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']179180 # 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