Merge branch 'feature/primary-sessions' 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 4d97cc7, 2b3bd78 · Browse files · 7 files·+166 added−128 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+166 added−128 removed
- other:+166 added−128 removed
Provenance
- Commit
e418631- Tree
b550d53- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
4d97cc7- Parent 2
2b3bd78
7 files changed+166 added−128 removed
modified:requests/__init__.py+3 added-3 removed
13 unmodified lines14 15 """16 17 __title__ = 'requests'18-__version__ = '0.6.6'19-__build__ = 0x00060618+__version__ = '0.6.7'19+__build__ = 0x00060720 __author__ = 'Kenneth Reitz'21 __license__ = 'ISC'22 __copyright__ = 'Copyright 2011 Kenneth Reitz'23 5 unmodified lines29 from .status_codes import codes30 from .config import settings31 from .exceptions import (32 RequestException, AuthenticationError, Timeout, URLRequired,33- InvalidMethod, TooManyRedirects33+ TooManyRedirects34 )modified:requests/api.py+6 added-72 removed
9 unmodified lines10 :license: ISC, see LICENSE for more details.11 12 """13 14-from . import config15-from .models import Request, Response, AuthObject16-from .status_codes import codes17-from .hooks import dispatch_hook18-from .utils import cookiejar_from_dict, header_expand14+from .sessions import session15 20-16 __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):22 27- """Constructs and sends a :class:`Request <Request>`.28- Returns :class:`Response <Response>` object.29-30- :param method: method for the new :class:`Request` object.31- :param url: URL for the new :class:`Request` object.32- :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.33- :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.34- :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.35- :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.36- :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.37- :param auth: (optional) AuthObject to enable Basic HTTP Auth.38- :param timeout: (optional) Float describing the timeout of the request.39- :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.40- :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.41- :param return_response: (optional) If False, an un-sent Request object will returned.42- """43-44- method = str(method).upper()45-46- if cookies is None:47- cookies = {}48-49- cookies = cookiejar_from_dict(cookies)50-51- # Expand header values52- if headers:53- for k, v in headers.items() or {}:54- headers[k] = header_expand(v)55-56- args = dict(57- method = method,58- url = url,59- data = data,60- params = params,61- headers = headers,62- cookiejar = cookies,63- files = files,64- auth = auth,65- hooks = hooks,66- timeout = timeout or config.settings.timeout,67- allow_redirects = allow_redirects,68- proxies = proxies or config.settings.proxies,23+ s = session()24+ return s.request(25+ method, url, params, data, headers, cookies, files, auth,26+ timeout, allow_redirects, proxies, hooks, return_response27 )28 71- # Arguments manipulation hook.72- args = dispatch_hook('args', hooks, args)29 74- r = Request(**args)30 76- # Pre-request hook.77- r = dispatch_hook('pre_request', hooks, r)78-79- # Don't send if asked nicely.80- if not return_response:81- return r82-83- # Send the HTTP Request.84- r.send()85-86- # Post-request hook.87- r = dispatch_hook('post_request', hooks, r)88-89- # Response manipulation hook.90- r.response = dispatch_hook('response', hooks, r.response)91-92- return r.response93-94-31 def get(url, **kwargs):96-32 """Sends a GET request. Returns :class:`Response` object.33 34 :param url: URL for the new :class:`Request` object.35 :param **kwargs: Optional arguments that ``request`` takes.36 """37 103-38 kwargs.setdefault('allow_redirects', True)39 return request('GET', url, **kwargs)40 41 52 unmodified linesmodified:requests/exceptions.py+1 added-4 removed
10 unmodified lines11 request."""12 13 class AuthenticationError(RequestException):14 """The authentication credentials provided were invalid."""15- 15+16 class Timeout(RequestException):17 """The request timed out."""18 19 class URLRequired(RequestException):20 """A valid URL is required to make a request."""21 22-class InvalidMethod(RequestException):23- """An inappropriate method was attempted."""24-22 class TooManyRedirects(RequestException):23 """Too many redirects."""modified:requests/models.py+10 added-10 removed
22 unmodified lines23 from .packages.poster.encode import multipart_encode24 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_gzip26 from .status_codes import codes27-from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects27+from .exceptions import Timeout, URLRequired, TooManyRedirects28 29 30 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31 5 unmodified lines37 """38 39 def __init__(self,40 url=None, headers=dict(), files=None, method=None, data=dict(),41- params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,41+ params=dict(), auth=None, cookies=None, timeout=None, redirect=False,42 allow_redirects=False, proxies=None, hooks=None):43 44 #: Float describes the timeout of the request.45 # (Use socket.setdefaulttimeout() as fallback)44 unmodified lines90 #: :class:`AuthObject` to attach to :class:`Request <Request>`.91 self.auth = auth92 93 #: CookieJar to attach to :class:`Request <Request>`.94- self.cookiejar = cookiejar94+ self.cookies = cookies95 96 #: True if Request has been sent.97 self.sent = False98 32 unmodified lines131 """Creates appropriate opener object for urllib2."""132 133 _handlers = []134 135- if self.cookiejar is not None:136- _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))135+ if self.cookies is not None:136+ _handlers.append(urllib2.HTTPCookieProcessor(self.cookies))137 138 if self.auth:139 if not isinstance(self.auth.handler,140 (urllib2.AbstractBasicAuthHandler,49 unmodified lines190 try:191 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))192 response.raw = resp193 194- if self.cookiejar:195- response.cookies = dict_from_cookiejar(self.cookiejar)194+ if self.cookies:195+ response.cookies = dict_from_cookiejar(self.cookies)196 197 198 except AttributeError:199 pass43 unmodified lines243 method = self.method244 245 request = Request(246 url, self.headers, self.files, method,247- self.data, self.params, self.auth, self.cookiejar,247+ self.data, self.params, self.auth, self.cookies,248 redirect=True249 )250 request.send()251 r = request.response111 unmodified lines363 if settings.timeout_fallback:364 # restore global timeout365 socket.setdefaulttimeout(old_timeout)366 367- if self.cookiejar is not None:368- self.cookiejar.extract_cookies(resp, req)367+ if self.cookies is not None:368+ self.cookies.extract_cookies(resp, req)369 370 except (urllib2.HTTPError, urllib2.URLError), why:371 if hasattr(why, 'reason'):372 if isinstance(why.reason, socket.timeout):307 unmodified linesmodified:requests/sessions.py+142 added-37 removed
9 unmodified lines10 """11 12 import cookielib13 14-from . import api15-from .utils import add_dict_to_cookiejar14+from . import config15+from .models import Request16+from .hooks import dispatch_hook17+from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand18 19 18-20 def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.22 23 If a local key in the dictionary is set to None, it will be removed.1 unmodified line25 26 if default_kwarg is None:27 return local_kwarg28 29+ if isinstance(local_kwarg, basestring):30+ return local_kwarg31+32 if local_kwarg is None:33 return default_kwarg34 35 # Bypass if not a dictionary (e.g. timeout)36 if not hasattr(default_kwarg, 'items'):37 return local_kwarg38 35-36-39 # Update new values.40 kwargs = default_kwarg.copy()41 kwargs.update(local_kwarg)42 31 unmodified lines74 # Set up a CookieJar to be used by default75 self.cookies = cookielib.FileCookieJar()76 77 # Map and wrap requests.api methods76- self._map_api_methods()78+ # self._map_api_methods()79 80 81 def __repr__(self):82 return '<requests-client at 0x%x>' % (id(self))3 unmodified lines86 87 def __exit__(self, *args):88 pass89 88- def _map_api_methods(self):89- """Reads each available method from requests.api and decorates90- them with a wrapper, which inserts any instance-local attributes91- (from __attrs__) that have been set, combining them with **kwargs.90+ def request(self, method, url,91+ params=None, data=None, headers=None, cookies=None, files=None, auth=None,92+ timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True):93+94+ """Constructs and sends a :class:`Request <Request>`.95+ Returns :class:`Response <Response>` object.96+97+ :param method: method for the new :class:`Request` object.98+ :param url: URL for the new :class:`Request` object.99+ :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.100+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.101+ :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.102+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.103+ :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.104+ :param auth: (optional) AuthObject to enable Basic HTTP Auth.105+ :param timeout: (optional) Float describing the timeout of the request.106+ :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.107+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.108+ :param return_response: (optional) If False, an un-sent Request object will returned.109 """110 94- def pass_args(func):95- def wrapper_func(*args, **kwargs):111+ method = str(method).upper()112 97- # Argument collector.98- _kwargs = {}113+ if cookies is None:114+ cookies = {}115 100- # If a session request has a cookie_dict, inject the101- # values into the existing CookieJar instead.102- if isinstance(kwargs.get('cookies', None), dict):103- kwargs['cookies'] = add_dict_to_cookiejar(104- self.cookies, kwargs['cookies']105- )116+ if isinstance(cookies, dict):117+ cookies = add_dict_to_cookiejar(self.cookies, cookies)118 107- for attr in self.__attrs__:108- # for attr in ['headers',]:109- s_val = self.__dict__.get(attr)110- r_val = kwargs.get(attr)119+ cookies = cookiejar_from_dict(cookies)120 112- new_attr = merge_kwargs(r_val, s_val)121+ # Expand header values122+ if headers:123+ for k, v in headers.items() or {}:124+ headers[k] = header_expand(v)125 114- # Skip attributes that were set to None.115- if new_attr is not None:116- _kwargs[attr] = new_attr126+ args = dict(127+ method = method,128+ url = url,129+ data = data,130+ params = params,131+ headers = headers,132+ cookies = cookies,133+ files = files,134+ auth = auth,135+ hooks = hooks,136+ timeout = timeout or config.settings.timeout,137+ allow_redirects = allow_redirects,138+ proxies = proxies or config.settings.proxies,139+ )140 118- # Make sure we didn't miss anything.119- for (k, v) in kwargs.items():120- if k not in _kwargs:121- _kwargs[k] = v141+ for attr in self.__attrs__:142+ session_val = getattr(self, attr, None)143+ local_val = args.get(attr)144 123- return func(*args, **_kwargs)145+ args[attr] = merge_kwargs(local_val, session_val)146 125- return wrapper_func147+ # Arguments manipulation hook.148+ args = dispatch_hook('args', hooks, args)149 127- # Map and decorate each function available in requests.api128- map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),129- api.__all__)150+ r = Request(**args)151 152+ # Pre-request hook.153+ r = dispatch_hook('pre_request', hooks, r)154 155+ # Don't send if asked nicely.156+ if not return_response:157+ return r158+159+ # Send the HTTP Request.160+ r.send()161+162+ # Post-request hook.163+ r = dispatch_hook('post_request', hooks, r)164+165+ # Response manipulation hook.166+ r.response = dispatch_hook('response', hooks, r.response)167+168+ return r.response169+170+171+ def get(self, url, **kwargs):172+ """Sends a GET request. Returns :class:`Response` object.173+174+ :param url: URL for the new :class:`Request` object.175+ :param **kwargs: Optional arguments that ``request`` takes.176+ """177+178+ kwargs.setdefault('allow_redirects', True)179+ return self.request('GET', url, **kwargs)180+181+182+ def head(self, url, **kwargs):183+ """Sends a HEAD request. Returns :class:`Response` object.184+185+ :param url: URL for the new :class:`Request` object.186+ :param **kwargs: Optional arguments that ``request`` takes.187+ """188+189+ kwargs.setdefault('allow_redirects', True)190+ return self.request('HEAD', url, **kwargs)191+192+193+ def post(self, url, data='', **kwargs):194+ """Sends a POST request. Returns :class:`Response` object.195+196+ :param url: URL for the new :class:`Request` object.197+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.198+ :param **kwargs: Optional arguments that ``request`` takes.199+ """200+201+ return self.request('post', url, data=data, **kwargs)202+203+204+ def put(self, url, data='', **kwargs):205+ """Sends a PUT request. Returns :class:`Response` object.206+207+ :param url: URL for the new :class:`Request` object.208+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.209+ :param **kwargs: Optional arguments that ``request`` takes.210+ """211+212+ return self.request('put', url, data=data, **kwargs)213+214+215+ def patch(url, data='', **kwargs):216+ """Sends a PATCH request. Returns :class:`Response` object.217+218+ :param url: URL for the new :class:`Request` object.219+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.220+ :param **kwargs: Optional arguments that ``request`` takes.221+ """222+223+ return self.request('patch', url, data='', **kwargs)224+225+226+ def delete(self, url, **kwargs):227+ """Sends a DELETE request. Returns :class:`Response` object.228+229+ :param url: URL for the new :class:`Request` object.230+ :param **kwargs: Optional arguments that ``request`` takes.231+ """232+233+ return self.request('delete', url, **kwargs)234+235+236+237 def session(**kwargs):238 """Returns a :class:`Session` for context-management."""239 240 return Session(**kwargs)modified:HISTORY.rst+2 added
2 unmodified lines3 4 0.6.75 +++++6 7+* Sessions are now the primary interface.8+* Deprecated InvalidMethodException.9 * PATCH fix.10 11 12 0.6.6 (2011-10-19)192 unmodified linesmodified:test_requests.py+2 added-2 removed
15 unmodified lines16 except ImportError:17 import json18 19 20-20 # TODO: Detect an open port.21 PORT = os.environ.get('HTTPBIN_PORT', '7077')22 23 HTTPBIN_URL = 'http://0.0.0.0:%s/' % (PORT)21 unmodified lines45 global _httpbin46 47 if not _httpbin:48 50- self.httpbin = envoy.connect('gunicorn httpbin:app --bind=0.0.0.0:%s' % (PORT))49+ c = envoy.connect('gunicorn httpbin:app --bind=0.0.0.0:%s' % (PORT))50 51+ self.httpbin = c52 _httpbin = True53 time.sleep(1)54 55 445 unmodified lines