Skip to content
Myr

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

7 files+166 added−128 removed

modified:requests/__init__.py+3 added-3 removed
13 unmodified lines
1415"""1617__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 lines
29from .status_codes import codes30from .config import settings31from .exceptions import (32 RequestException, AuthenticationError, Timeout, URLRequired,33 InvalidMethod, TooManyRedirects33 TooManyRedirects34)
modified:requests/api.py+6 added-72 removed
9 unmodified lines
10:license: ISC, see LICENSE for more details.1112"""1314from . import config15from .models import Request, Response, AuthObject16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict, header_expand14from .sessions import session152016__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):2227 """Constructs and sends a :class:`Request <Request>`.28 Returns :class:`Response <Response>` object.2930 :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 """4344 method = str(method).upper()4546 if cookies is None:47 cookies = {}4849 cookies = cookiejar_from_dict(cookies)5051 # Expand header values52 if headers:53 for k, v in headers.items() or {}:54 headers[k] = header_expand(v)5556 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 )2871 # Arguments manipulation hook.72 args = dispatch_hook('args', hooks, args)2974 r = Request(**args)3076 # Pre-request hook.77 r = dispatch_hook('pre_request', hooks, r)7879 # Don't send if asked nicely.80 if not return_response:81 return r8283 # Send the HTTP Request.84 r.send()8586 # Post-request hook.87 r = dispatch_hook('post_request', hooks, r)8889 # Response manipulation hook.90 r.response = dispatch_hook('response', hooks, r.response)9192 return r.response939431def get(url, **kwargs):9632 """Sends a GET request. Returns :class:`Response` object.3334 :param url: URL for the new :class:`Request` object.35 :param **kwargs: Optional arguments that ``request`` takes.36 """3710338 kwargs.setdefault('allow_redirects', True)39 return request('GET', url, **kwargs)4041
52 unmodified lines
modified:requests/exceptions.py+1 added-4 removed
10 unmodified lines
11 request."""1213class AuthenticationError(RequestException):14 """The authentication credentials provided were invalid."""15 1516class Timeout(RequestException):17 """The request timed out."""1819class URLRequired(RequestException):20 """A valid URL is required to make a request."""2122class InvalidMethod(RequestException):23 """An inappropriate method was attempted."""2422class TooManyRedirects(RequestException):23 """Too many redirects."""
modified:requests/models.py+10 added-10 removed
22 unmodified lines
23from .packages.poster.encode import multipart_encode24from .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_gzip26from .status_codes import codes27from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects27from .exceptions import Timeout, URLRequired, TooManyRedirects282930REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31
5 unmodified lines
37 """3839 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):4344 #: Float describes the timeout of the request.45 # (Use socket.setdefaulttimeout() as fallback)
44 unmodified lines
90 #: :class:`AuthObject` to attach to :class:`Request <Request>`.91 self.auth = auth9293 #: CookieJar to attach to :class:`Request <Request>`.94 self.cookiejar = cookiejar94 self.cookies = cookies9596 #: True if Request has been sent.97 self.sent = False98
32 unmodified lines
131 """Creates appropriate opener object for urllib2."""132133 _handlers = []134135 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))137138 if self.auth:139 if not isinstance(self.auth.handler,140 (urllib2.AbstractBasicAuthHandler,
49 unmodified lines
190 try:191 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))192 response.raw = resp193194 if self.cookiejar:195 response.cookies = dict_from_cookiejar(self.cookiejar)194 if self.cookies:195 response.cookies = dict_from_cookiejar(self.cookies)196197198 except AttributeError:199 pass
43 unmodified lines
243 method = self.method244245 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.response
111 unmodified lines
363 if settings.timeout_fallback:364 # restore global timeout365 socket.setdefaulttimeout(old_timeout)366367 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)369370 except (urllib2.HTTPError, urllib2.URLError), why:371 if hasattr(why, 'reason'):372 if isinstance(why.reason, socket.timeout):
307 unmodified lines
modified:requests/sessions.py+142 added-37 removed
9 unmodified lines
10"""1112import cookielib1314from . import api15from .utils import add_dict_to_cookiejar14from . import config15from .models import Request16from .hooks import dispatch_hook17from .utils import add_dict_to_cookiejar, cookiejar_from_dict, header_expand18191820def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.2223 If a local key in the dictionary is set to None, it will be removed.
1 unmodified line
2526 if default_kwarg is None:27 return local_kwarg2829 if isinstance(local_kwarg, basestring):30 return local_kwarg3132 if local_kwarg is None:33 return default_kwarg3435 # Bypass if not a dictionary (e.g. timeout)36 if not hasattr(default_kwarg, 'items'):37 return local_kwarg38353639 # Update new values.40 kwargs = default_kwarg.copy()41 kwargs.update(local_kwarg)42
31 unmodified lines
74 # Set up a CookieJar to be used by default75 self.cookies = cookielib.FileCookieJar()7677 # Map and wrap requests.api methods76 self._map_api_methods()78 # self._map_api_methods()798081 def __repr__(self):82 return '<requests-client at 0x%x>' % (id(self))
3 unmodified lines
8687 def __exit__(self, *args):88 pass8988 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):9394 """Constructs and sends a :class:`Request <Request>`.95 Returns :class:`Response <Response>` object.9697 :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 """11094 def pass_args(func):95 def wrapper_func(*args, **kwargs):111 method = str(method).upper()11297 # Argument collector.98 _kwargs = {}113 if cookies is None:114 cookies = {}115100 # 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)118107 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)120112 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)125114 # 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 )140118 # 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)144123 return func(*args, **_kwargs)145 args[attr] = merge_kwargs(local_val, session_val)146125 return wrapper_func147 # Arguments manipulation hook.148 args = dispatch_hook('args', hooks, args)149127 # 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)151152 # Pre-request hook.153 r = dispatch_hook('pre_request', hooks, r)154155 # Don't send if asked nicely.156 if not return_response:157 return r158159 # Send the HTTP Request.160 r.send()161162 # Post-request hook.163 r = dispatch_hook('post_request', hooks, r)164165 # Response manipulation hook.166 r.response = dispatch_hook('response', hooks, r.response)167168 return r.response169170171 def get(self, url, **kwargs):172 """Sends a GET request. Returns :class:`Response` object.173174 :param url: URL for the new :class:`Request` object.175 :param **kwargs: Optional arguments that ``request`` takes.176 """177178 kwargs.setdefault('allow_redirects', True)179 return self.request('GET', url, **kwargs)180181182 def head(self, url, **kwargs):183 """Sends a HEAD request. Returns :class:`Response` object.184185 :param url: URL for the new :class:`Request` object.186 :param **kwargs: Optional arguments that ``request`` takes.187 """188189 kwargs.setdefault('allow_redirects', True)190 return self.request('HEAD', url, **kwargs)191192193 def post(self, url, data='', **kwargs):194 """Sends a POST request. Returns :class:`Response` object.195196 :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 """200201 return self.request('post', url, data=data, **kwargs)202203204 def put(self, url, data='', **kwargs):205 """Sends a PUT request. Returns :class:`Response` object.206207 :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 """211212 return self.request('put', url, data=data, **kwargs)213214215 def patch(url, data='', **kwargs):216 """Sends a PATCH request. Returns :class:`Response` object.217218 :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 """222223 return self.request('patch', url, data='', **kwargs)224225226 def delete(self, url, **kwargs):227 """Sends a DELETE request. Returns :class:`Response` object.228229 :param url: URL for the new :class:`Request` object.230 :param **kwargs: Optional arguments that ``request`` takes.231 """232233 return self.request('delete', url, **kwargs)234235236237def session(**kwargs):238 """Returns a :class:`Session` for context-management."""239240 return Session(**kwargs)
modified:HISTORY.rst+2 added
2 unmodified lines
340.6.75+++++67* Sessions are now the primary interface.8* Deprecated InvalidMethodException.9* PATCH fix.1011120.6.6 (2011-10-19)
192 unmodified lines
modified:test_requests.py+2 added-2 removed
15 unmodified lines
16except ImportError:17 import json18192020# TODO: Detect an open port.21PORT = os.environ.get('HTTPBIN_PORT', '7077')2223HTTPBIN_URL = 'http://0.0.0.0:%s/' % (PORT)
21 unmodified lines
45 global _httpbin4647 if not _httpbin:4850 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))5051 self.httpbin = c52 _httpbin = True53 time.sleep(1)5455
445 unmodified lines