new local merging of keyword arguments for sessions
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 9645e88 · Browse files · 1 file·+65 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+65 added−16 removed
- other:+65 added−16 removed
Provenance
- Commit
65a765f- Tree
f936062- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
9645e88
1 file changed+65 added−16 removed
modified:requests/sessions.py+65 added-16 removed
14 unmodified lines15 from .utils import add_dict_to_cookiejar16 17 18 19+def merge_kwargs(local_kwarg, default_kwarg):20+ """Merges kwarg dictionaries.21+22+ If a local key in the dictionary is set to None, it will be removed.23+ """24+25+ if default_kwarg is None:26+ return local_kwarg27+28+ if local_kwarg is None:29+ return default_kwarg30+31+ # Bypass if not a dictionary (e.g. timeout)32+ if not hasattr(default_kwarg, 'items'):33+ return local_kwarg34+35+36+37+ # Update new values.38+ kwargs = default_kwarg.copy()39+ kwargs.update(local_kwarg)40+41+ # Remove keys that are set to None.42+ for (k,v) in local_kwarg.items():43+ if v is None:44+ del kwargs[k]45+46+ return kwargs47+48+49 class Session(object):50 """A Requests session."""51 52 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']53 54 25- def __init__(self, **kwargs):55+ def __init__(self,56+ headers=None,57+ cookies=None,58+ auth=None,59+ timeout=None,60+ proxies=None,61+ hooks=None):62 63+ self.headers = headers or {}64+ self.cookies = cookies or {}65+ self.auth = auth66+ self.timeout = timeout67+ self.proxies = proxies or {}68+ self.hooks = hooks or {}69+70 # Set up a CookieJar to be used by default71 self.cookies = cookielib.FileCookieJar()72 30- # Map args from kwargs to instance-local variables31- map(lambda k, v: (k in self.__attrs__) and setattr(self, k, v),32- kwargs.iterkeys(), kwargs.itervalues())33-73 # Map and wrap requests.api methods74 self._map_api_methods()75 76 3 unmodified lines80 def __enter__(self):81 return self82 83 def __exit__(self, *args):45- # print args84 pass85 48-86 def _map_api_methods(self):87 """Reads each available method from requests.api and decorates88 them with a wrapper, which inserts any instance-local attributes89 (from __attrs__) that have been set, combining them with **kwargs.90 """91 92 def pass_args(func):93 def wrapper_func(*args, **kwargs):57- inst_attrs = dict((k, v) for k, v in self.__dict__.iteritems()58- if k in self.__attrs__)59- # Combine instance-local values with kwargs values, with60- # priority to values in kwargs61- kwargs = dict(inst_attrs.items() + kwargs.items())94 95+ # Argument collector.96+ _kwargs = {}97+98 # If a session request has a cookie_dict, inject the99 # values into the existing CookieJar instead.100 if isinstance(kwargs.get('cookies', None), dict):101 kwargs['cookies'] = add_dict_to_cookiejar(67- inst_attrs['cookies'], kwargs['cookies']102+ self.cookies, kwargs['cookies']103 )104 70- if kwargs.get('headers', None) and inst_attrs.get('headers', None):71- kwargs['headers'].update(inst_attrs['headers'])105+ for attr in self.__attrs__:106+ # for attr in ['headers',]:107+ s_val = self.__dict__.get(attr)108+ r_val = kwargs.get(attr)109 110+ new_attr = merge_kwargs(r_val, s_val)111+112+ # Skip attributes that were set to None.113+ if new_attr is not None:114+ _kwargs[attr] = new_attr115+116+ # Make sure we didn't miss anything.117+ for (k, v) in kwargs.items():118+ if k not in _kwargs:119+ _kwargs[k] = v120+73- return func(*args, **kwargs)121+ return func(*args, **_kwargs)122+123 return wrapper_func124 125 # Map and decorate each function available in requests.api126 map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),7 unmodified lines