Skip to content
Myr

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

4 files+18 added−261 removed

modified:requests/api.py+8 added-8 removed
12 unmodified lines
1314from ._config import get_config15from .models import Request, Response16from .status_codes import codes17from hooks import setup_hooks, dispatch_hooks17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict, header_expand192021__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')
23 unmodified lines
4546 method = str(method).upper()47 config = get_config(config)4849 # cookies = cookiejar_from_dict(cookies if cookies is not None else dict())49 if cookies is None:50 cookies = {}5152 # cookies = cookiejar_from_dict(cookies)5354 # Expand header values55 if headers:
15 unmodified lines
71 proxies=proxies or config.get('proxies'),72 _pools=_pools73 )7473 hooks = setup_hooks(hooks if hooks is not None else dict())7475 # Arguments manipulation hook.76 args = dispatch_hooks(hooks['args'], args)76 args = dispatch_hook('args', hooks, args)7778 # Create Request object.79 r = Request(**args)8081 # Pre-request hook.82 r = dispatch_hooks(hooks['pre_request'], r)82 r = dispatch_hook('pre_request', hooks, r)8384 # Only construct the request (for async)85 if _return_request:86 return r
2 unmodified lines
89 r.send()9091 # 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)9495 # Response manipulation hook.96 r.response = dispatch_hooks(hooks['response'], r.response)96 r.response = dispatch_hook('response', hooks, r.response)9798 return r.response99100
67 unmodified lines
deleted:requests/config.py-80 removed
1# -*- coding: utf-8 -*-23"""4requests.config5~~~~~~~~~~~~~~~67This module provides the Requests settings feature set.89"""1011class Settings(object):12 _singleton = {}1314 # attributes with defaults15 __attrs__ = []1617 def __init__(self, **kwargs):18 super(Settings, self).__init__()1920 self.__dict__ = self._singleton212223 def __call__(self, *args, **kwargs):24 # new instance of class to call25 r = self.__class__()2627 # cache previous settings for __exit__28 r.__cache = self.__dict__.copy()29 map(self.__cache.setdefault, self.__attrs__)3031 # set new settings32 self.__dict__.update(*args, **kwargs)3334 return r353637 def __enter__(self):38 pass394041 def __exit__(self, *args):4243 # restore cached copy44 self.__dict__.update(self.__cache.copy())45 del self.__cache464748 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)555657settings = Settings()5859settings.base_headers = {60 'User-Agent': 'python-requests.org',61 'Accept-Encoding': ', '.join([ 'identity', 'deflate', 'compress', 'gzip' ]),62}63settings.accept_gzip = True64settings.proxies = None65settings.verbose = None66settings.timeout = None67settings.max_redirects = 3068settings.decode_unicode = False69settings.gracefull_hooks = True7071#: A dictionary of default hooks to be applied, based on settings.72settings.default_hooks = {73 'args': list(),74 'pre_request': list(),75 'post_request': list(),76 'response': list()77}7879#: Use socket.setdefaulttimeout() as fallback?80settings.timeout_fallback = True
modified:requests/hooks.py+7 added-150 removed
21 unmodified lines
2223"""2425import warnings26from collections import Iterable27import config28import zlib29import bz230from cgi import parse_header26import collections2732def 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**.2836 :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 """29def dispatch_hook(key, hooks, hook_data):30 """Dipatches a hook dictionary on a given peice of data."""3143 # 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]3447 # 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 """35 for hook in hooks:36 try:84 # hook must be a callable.85 data = hook(data)8637 hook_data = hook(hook_data) or hook_data38 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: raise9439 warnings.warn(str(why))4097 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 r41 return hook_data
modified:requests/models.py+3 added-23 removed
451 unmodified lines
452 """Content of the response, in bytes or unicode453 (if available).454 """455456 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._content458459 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 # pass462470 self._content = self.fo.read()463 # Read the contents.464 self._content = self.raw.read() or self.raw.data465466 # Decode GZip'd content.467 if 'gzip' in self.headers.get('content-encoding', ''):
2 unmodified lines
470 except zlib.error:471 pass472473 # 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 pass489490 # 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)476477 self._content_consumed = True478 return self._content479
17 unmodified lines