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
Provenance
- Commit
d72d116- Tree
0af9991- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
d552e6c
2 files changed+92 added−103 removed
modified:requests/api.py+6 added-66 removed
14 unmodified lines15 from .models import Request, Response, AuthObject16 from .status_codes import codes17 from .hooks import dispatch_hook18 from .utils import cookiejar_from_dict, header_expand19+from .sessions import session20 20-21 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')22 23+24 def 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):27 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,28+ s = session()29+ return s.request(30+ method, url, params, data, headers, cookies, files, auth,31+ timeout, allow_redirects, proxies, hooks, return_response32 )33 71- # Arguments manipulation hook.72- args = dispatch_hook('args', hooks, args)34 74- r = Request(**args)35 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-36 def get(url, **kwargs):96-37 """Sends a GET request. Returns :class:`Response` object.38 39 :param url: URL for the new :class:`Request` object.40 :param **kwargs: Optional arguments that ``request`` takes.59 unmodified linesmodified:requests/sessions.py+86 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+ def get(self, url, **kwargs):171+ """Sends a GET request. Returns :class:`Response` object.172+173+ :param url: URL for the new :class:`Request` object.174+ :param **kwargs: Optional arguments that ``request`` takes.175+ """176+177+ kwargs.setdefault('allow_redirects', True)178+ return self.request('GET', url, **kwargs)179+180+181 def session(**kwargs):182 """Returns a :class:`Session` for context-management."""183 184 return Session(**kwargs)