Merge branch 'feature/config' into develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 185450c, 8c34fa8 · Browse files · 8 files·+145 added−113 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+145 added−113 removed
- other:+145 added−113 removed
Provenance
- Commit
f0fe8b9- Tree
3235640- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
185450c- Parent 2
8c34fa8
8 files changed+145 added−113 removed
modified:docs/user/advanced.rst+2 added-2 removed
37 unmodified lines38 39 40 .. admonition:: Global Settings41 42- Certain parameters are best set at the ``request.config`` level43- (e.g.. a global proxy, user agent header).42+ Certain parameters are best set in the ``config`` dictionary43+ (e.g. user agent header).44 45 46 Asynchronous Requests47 ----------------------125 unmodified linesmodified:requests/__init__.py-1 removed
25 unmodified lines26 from .models import HTTPError, Request, Response27 from .api import request, get, head, post, patch, put, delete28 from .sessions import session29 from .status_codes import codes30-from .config import settings30 from .exceptions import (31 RequestException, AuthenticationError, Timeout, URLRequired,32 TooManyRedirects33 )modified:requests/api.py+14 added-3 removed
15 unmodified lines16 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')17 18 19 def request(method, url,20- params=None, data=None, headers=None, cookies=None, files=None, auth=None,21- timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True):20+ params=None,21+ data=None,22+ headers=None,23+ cookies=None,24+ files=None,25+ auth=None,26+ timeout=None,27+ allow_redirects=False,28+ proxies=None,29+ hooks=None,30+ return_response=True,31+ config=None):32 33 s = session()34 return s.request(35 method, url, params, data, headers, cookies, files, auth,26- timeout, allow_redirects, proxies, hooks, return_response36+ timeout, allow_redirects, proxies, hooks, return_response,37+ config38 )39 40 41 63 unmodified linesdeleted:requests/config.py-68 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 = {'User-Agent': 'python-requests.org'}60-settings.accept_gzip = True61-settings.proxies = None62-settings.verbose = None63-settings.timeout = None64-settings.max_redirects = 3065-settings.decode_unicode = True66-67-#: Use socket.setdefaulttimeout() as fallback?68-settings.timeout_fallback = Trueadded:requests/defaults.py+48 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.defaults5+~~~~~~~~~~~~~~~~~6+7+This module provides the Requests configuration defaults.8+9+settings parameters:10+11+- :base_headers: - Sets default User-Agent to `python-requests.org`12+- :accept_gzip: - Whether or not to accept gzip-compressed data13+- :proxies: - http proxies?14+- :verbose: - display verbose information?15+- :timeout: - timeout time until request terminates16+- :max_redirects: - maximum number of allowed redirects?17+- :decode_unicode: - whether or not to accept unicode?18+19+"""20+21+from . import __version__22+23+defaults = dict()24+25+26+defaults['base_headers'] = {27+ 'User-Agent': 'python-requests/{0}'.format(__version__),28+ 'Accept-Encoding': ', '.join([ 'identity', 'deflate', 'compress', 'gzip' ]),29+}30+31+32+# defaults['accept_gzip'] = True33+defaults['proxies'] = {}34+defaults['verbose'] = None35+defaults['timeout'] = None36+defaults['max_redirects'] = 3037+defaults['decode_unicode'] = True38+defaults['timeout_fallback'] = True39+# defaults['keep_alive'] = True40+# defaults['max_connections'] = 1041+42+43+# defaults['hooks'] = {44+# 'args': list(),45+# 'pre_request': list(),46+# 'post_request': list(),47+# 'response': list()48+# }modified:requests/models.py+46 added-22 removed
7 unmodified lines8 9 import urllib10 import urllib211 import socket12-import codecs12 import zlib13 15-14 from urllib2 import HTTPError15 from urlparse import urlparse, urlunparse, urljoin16 from datetime import datetime17 20-from .config import settings21-from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler18 from .structures import CaseInsensitiveDict19 from .packages.poster.encode import multipart_encode20 from .packages.poster.streaminghttp import register_openers, get_handlers25-from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip21+from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)22 from .status_codes import codes23 from .exceptions import Timeout, URLRequired, TooManyRedirects24+from .monkeys import Request as _Request25+from .monkeys import (26+ HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler,27+ HTTPDigestAuthHandler, HTTPRedirectHandler)28 29 30 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31 4 unmodified lines36 Requests. Recommended interface is with the Requests functions.37 """38 39 def __init__(self,40- url=None, headers=dict(), files=None, method=None, data=dict(),41- params=dict(), auth=None, cookies=None, timeout=None, redirect=False,42- allow_redirects=False, proxies=None, hooks=None):40+ url=None,41+ headers=dict(),42+ files=None,43+ method=None,44+ data=dict(),45+ params=dict(),46+ auth=None,47+ cookies=None,48+ timeout=None,49+ redirect=False,50+ allow_redirects=False,51+ proxies=None,52+ hooks=None,53+ config=None):54 55 #: Float describes the timeout of the request.56 # (Use socket.setdefaulttimeout() as fallback)57 self.timeout = timeout45 unmodified lines103 104 #: CookieJar to attach to :class:`Request <Request>`.105 self.cookies = cookies106 107+ #: Dictionary of configurations for this request.108+ self.config = config109+110 #: True if Request has been sent.111 self.sent = False112 113 #: Event-handling hooks.114 self.hooks = hooks115 116 # Header manipulation and defaults.117+ if self.config.get('accept_gzip'):118+ self.headers.update({'Accept-Encoding': 'gzip'})119 104- if settings.accept_gzip:105- settings.base_headers.update({'Accept-Encoding': 'gzip'})106-120 if headers:121 headers = CaseInsensitiveDict(self.headers)122 else:123 headers = CaseInsensitiveDict()124 112- for (k, v) in settings.base_headers.items():125+ for (k, v) in self.config.get('base_headers', {}).items():126 if k not in headers:127 headers[k] = v128 129 self.headers = headers67 unmodified lines197 198 def build(resp):199 200 response = Response()201+ response.config = self.config202 response.status_code = getattr(resp, 'code', None)203 204 try:205 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))26 unmodified lines232 ):233 234 r.raw.close()235 222- if not len(history) < settings.max_redirects:236+ if not len(history) < self.config.get('max_redirects'):237 raise TooManyRedirects()238 239 history.append(r)240 15 unmodified lines256 else:257 method = self.method258 259 request = Request(246- url, self.headers, self.files, method,247- self.data, self.params, self.auth, self.cookies,248- redirect=True260+ url=url,261+ headers=self.headers,262+ files=self.files,263+ method=method,264+ # data=self.data,265+ # params=self.params,266+ auth=self.auth,267+ cookies=self.cookies,268+ redirect=True,269+ config=self.config270 )271 request.send()272 r = request.response273 59 unmodified lines333 334 self._checks()335 336 # Logging316- if settings.verbose:317- settings.verbose.write('%s %s %s\n' % (337+ if self.config.get('verbose'):338+ self.config.get('verbose').write('%s %s %s\n' % (339 datetime.now().isoformat(), self.method, self.url340 ))341 342 30 unmodified lines373 # timeout argument is new since Python v2.6374 if not 'timeout' in str(err):375 raise376 356- if settings.timeout_fallback:377+ if self.config.get('timeout_fallback'):378 # fall-back and use global socket timeout (This is not thread-safe!)379 old_timeout = socket.getdefaulttimeout()380 socket.setdefaulttimeout(self.timeout)381 382 resp = opener(req)383 363- if settings.timeout_fallback:384+ if self.config.get('timeout_fallback'):385 # restore global timeout386 socket.setdefaulttimeout(old_timeout)387 388 if self.cookies is not None:60 unmodified lines449 450 #: A dictionary of Cookies the server sent back.451 self.cookies = None452 453+ #: Dictionary of configurations for this request.454+ self.config = None455 456+457 def __repr__(self):458 return '<Response [%s]>' % (self.status_code)459 460 22 unmodified lines483 gen = generate()484 if 'gzip' in self.headers.get('content-encoding', ''):485 gen = stream_decode_gzip(gen)486 if decode_unicode is None:463- decode_unicode = settings.decode_unicode487+ decode_unicode = self.config.get('decode_unicode')488 if decode_unicode:489 gen = stream_decode_response_unicode(gen, self)490 return gen491 20 unmodified lines512 except zlib.error:513 pass514 515 # Decode unicode content.492- if settings.decode_unicode:516+ if self.config.get('decode_unicode'):517 self._content = get_unicode_from_response(self)518 519 self._content_consumed = True520 return self._content183 unmodified linesmodified:requests/sessions.py+34 added-17 removed
9 unmodified lines10 """11 12 import cookielib13 14-from . import config14+from .defaults import defaults15 from .models import Request16 from .hooks import dispatch_hook17 from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand18 31 unmodified lines50 51 class Session(object):52 """A Requests session."""53 54- __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params']54+ __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params', 'config']55 56 57 def __init__(self,58 headers=None,1 unmodified line60 auth=None,61 timeout=None,62 proxies=None,63 hooks=None,64- params=None):64+ params=None,65+ config=None):66 67 self.headers = headers or {}68 self.cookies = cookies or {}69 self.auth = auth70 self.timeout = timeout71 self.proxies = proxies or {}72 self.hooks = hooks or {}73 self.params = params or {}74+ self.config = config or {}75 76+ for (k, v) in defaults.items():77+ self.config.setdefault(k, v)78+79 # Set up a CookieJar to be used by default80 self.cookies = cookielib.FileCookieJar()81 82 def __repr__(self):5 unmodified lines88 def __exit__(self, *args):89 pass90 91 def request(self, method, url,87- params=None, data=None, headers=None, cookies=None, files=None, auth=None,88- timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True):92+ params=None,93+ data=None,94+ headers=None,95+ cookies=None,96+ files=None,97+ auth=None,98+ timeout=None,99+ allow_redirects=False,100+ proxies=None,101+ hooks=None,102+ return_response=True,103+ config=None):104 105 """Constructs and sends a :class:`Request <Request>`.106 Returns :class:`Response <Response>` object.107 8 unmodified lines116 :param timeout: (optional) Float describing the timeout of the request.117 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.118 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.119 :param return_response: (optional) If False, an un-sent Request object will returned.120+ :param config: (optional) A configuration dictionary.121 """122 123 method = str(method).upper()124 10 unmodified lines135 for k, v in headers.items() or {}:136 headers[k] = header_expand(v)137 138 args = dict(123- method = method,124- url = url,125- data = data,126- params = params,127- headers = headers,128- cookies = cookies,129- files = files,130- auth = auth,131- hooks = hooks,132- timeout = timeout or config.settings.timeout,133- allow_redirects = allow_redirects,134- proxies = proxies or config.settings.proxies,139+ method=method,140+ url=url,141+ data=data,142+ params=params,143+ headers=headers,144+ cookies=cookies,145+ files=files,146+ auth=auth,147+ hooks=hooks,148+ timeout=timeout,149+ allow_redirects=allow_redirects,150+ proxies=proxies,151+ config=config152 )153 154 for attr in self.__attrs__:155 session_val = getattr(self, attr, None)98 unmodified linesmodified:HISTORY.rst+1 added
5 unmodified lines6 7 * Sessions are now the primary interface.8 * Deprecated InvalidMethodException.9 * PATCH fix.10+* New config system (no more global settings).11 12 13 0.6.6 (2011-10-19)14 ++++++++++++++++++191 unmodified lines