Skip to content
Myr

Move request and get to session

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 · parent d552e6c · Browse files · 2 files+92 added−103 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+92 added−103 removed

  • other:+92 added−103 removed

2 files+92 added−103 removed

modified:requests/api.py+6 added-66 removed
14 unmodified lines
15from .models import Request, Response, AuthObject16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict, header_expand19from .sessions import session202021__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')222324def request(method, url,25 params=None, data=None, headers=None, cookies=None, files=None, auth=None,26 timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True):2727 """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,28 s = session()29 return s.request(30 method, url, params, data, headers, cookies, files, auth,31 timeout, allow_redirects, proxies, hooks, return_response32 )3371 # Arguments manipulation hook.72 args = dispatch_hook('args', hooks, args)3474 r = Request(**args)3576 # 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.response939436def get(url, **kwargs):9637 """Sends a GET request. Returns :class:`Response` object.3839 :param url: URL for the new :class:`Request` object.40 :param **kwargs: Optional arguments that ``request`` takes.
59 unmodified lines
modified:requests/sessions.py+86 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.response169170 def get(self, url, **kwargs):171 """Sends a GET request. Returns :class:`Response` object.172173 :param url: URL for the new :class:`Request` object.174 :param **kwargs: Optional arguments that ``request`` takes.175 """176177 kwargs.setdefault('allow_redirects', True)178 return self.request('GET', url, **kwargs)179180181def session(**kwargs):182 """Returns a :class:`Session` for context-management."""183184 return Session(**kwargs)