Skip to content
Myr

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

8 files+145 added−113 removed

modified:docs/user/advanced.rst+2 added-2 removed
37 unmodified lines
383940.. admonition:: Global Settings4142 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).444546Asynchronous Requests47----------------------
125 unmodified lines
modified:requests/__init__.py-1 removed
25 unmodified lines
26from .models import HTTPError, Request, Response27from .api import request, get, head, post, patch, put, delete28from .sessions import session29from .status_codes import codes30from .config import settings30from .exceptions import (31 RequestException, AuthenticationError, Timeout, URLRequired,32 TooManyRedirects33)
modified:requests/api.py+14 added-3 removed
15 unmodified lines
16__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')171819def 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):3233 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 )394041
63 unmodified lines
deleted:requests/config.py-68 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 = {'User-Agent': 'python-requests.org'}60settings.accept_gzip = True61settings.proxies = None62settings.verbose = None63settings.timeout = None64settings.max_redirects = 3065settings.decode_unicode = True6667#: Use socket.setdefaulttimeout() as fallback?68settings.timeout_fallback = True
added:requests/defaults.py+48 added
1# -*- coding: utf-8 -*-23"""4requests.defaults5~~~~~~~~~~~~~~~~~67This module provides the Requests configuration defaults.89settings parameters:1011- :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?1819"""2021from . import __version__2223defaults = dict()242526defaults['base_headers'] = {27 'User-Agent': 'python-requests/{0}'.format(__version__),28 'Accept-Encoding': ', '.join([ 'identity', 'deflate', 'compress', 'gzip' ]),29}303132# defaults['accept_gzip'] = True33defaults['proxies'] = {}34defaults['verbose'] = None35defaults['timeout'] = None36defaults['max_redirects'] = 3037defaults['decode_unicode'] = True38defaults['timeout_fallback'] = True39# defaults['keep_alive'] = True40# defaults['max_connections'] = 10414243# 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 lines
89import urllib10import urllib211import socket12import codecs12import zlib131514from urllib2 import HTTPError15from urlparse import urlparse, urlunparse, urljoin16from datetime import datetime1720from .config import settings21from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler18from .structures import CaseInsensitiveDict19from .packages.poster.encode import multipart_encode20from .packages.poster.streaminghttp import register_openers, get_handlers25from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip21from .utils import (dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip)22from .status_codes import codes23from .exceptions import Timeout, URLRequired, TooManyRedirects24from .monkeys import Request as _Request25from .monkeys import (26 HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler,27 HTTPDigestAuthHandler, HTTPRedirectHandler)282930REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31
4 unmodified lines
36 Requests. Recommended interface is with the Requests functions.37 """3839 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):5455 #: Float describes the timeout of the request.56 # (Use socket.setdefaulttimeout() as fallback)57 self.timeout = timeout
45 unmodified lines
103104 #: CookieJar to attach to :class:`Request <Request>`.105 self.cookies = cookies106107 #: Dictionary of configurations for this request.108 self.config = config109110 #: True if Request has been sent.111 self.sent = False112113 #: Event-handling hooks.114 self.hooks = hooks115116 # Header manipulation and defaults.117 if self.config.get('accept_gzip'):118 self.headers.update({'Accept-Encoding': 'gzip'})119104 if settings.accept_gzip:105 settings.base_headers.update({'Accept-Encoding': 'gzip'})106120 if headers:121 headers = CaseInsensitiveDict(self.headers)122 else:123 headers = CaseInsensitiveDict()124112 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] = v128129 self.headers = headers
67 unmodified lines
197198 def build(resp):199200 response = Response()201 response.config = self.config202 response.status_code = getattr(resp, 'code', None)203204 try:205 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))
26 unmodified lines
232 ):233234 r.raw.close()235222 if not len(history) < settings.max_redirects:236 if not len(history) < self.config.get('max_redirects'):237 raise TooManyRedirects()238239 history.append(r)240
15 unmodified lines
256 else:257 method = self.method258259 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 lines
333334 self._checks()335336 # 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 ))341342
30 unmodified lines
373 # timeout argument is new since Python v2.6374 if not 'timeout' in str(err):375 raise376356 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)381382 resp = opener(req)383363 if settings.timeout_fallback:384 if self.config.get('timeout_fallback'):385 # restore global timeout386 socket.setdefaulttimeout(old_timeout)387388 if self.cookies is not None:
60 unmodified lines
449450 #: A dictionary of Cookies the server sent back.451 self.cookies = None452453 #: Dictionary of configurations for this request.454 self.config = None455456457 def __repr__(self):458 return '<Response [%s]>' % (self.status_code)459460
22 unmodified lines
483 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 lines
512 except zlib.error:513 pass514515 # Decode unicode content.492 if settings.decode_unicode:516 if self.config.get('decode_unicode'):517 self._content = get_unicode_from_response(self)518519 self._content_consumed = True520 return self._content
183 unmodified lines
modified:requests/sessions.py+34 added-17 removed
9 unmodified lines
10"""1112import cookielib1314from . import config14from .defaults import defaults15from .models import Request16from .hooks import dispatch_hook17from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand18
31 unmodified lines
5051class Session(object):52 """A Requests session."""5354 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params']54 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', 'params', 'config']555657 def __init__(self,58 headers=None,
1 unmodified line
60 auth=None,61 timeout=None,62 proxies=None,63 hooks=None,64 params=None):64 params=None,65 config=None):6667 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 {}7576 for (k, v) in defaults.items():77 self.config.setdefault(k, v)7879 # Set up a CookieJar to be used by default80 self.cookies = cookielib.FileCookieJar()8182 def __repr__(self):
5 unmodified lines
88 def __exit__(self, *args):89 pass9091 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):104105 """Constructs and sends a :class:`Request <Request>`.106 Returns :class:`Response <Response>` object.107
8 unmodified lines
116 :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 """122123 method = str(method).upper()124
10 unmodified lines
135 for k, v in headers.items() or {}:136 headers[k] = header_expand(v)137138 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 )153154 for attr in self.__attrs__:155 session_val = getattr(self, attr, None)
98 unmodified lines
modified:HISTORY.rst+1 added
5 unmodified lines
67* Sessions are now the primary interface.8* Deprecated InvalidMethodException.9* PATCH fix.10* New config system (no more global settings).1112130.6.6 (2011-10-19)14++++++++++++++++++
191 unmodified lines