Merge pull request #3885 from davidfontenot/cache_proxy_bypass
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Cache proxy bypass
authored by Cory Benfield · committed by GitHub · parents d6f4818, c121b98 · Browse files · 4 files·+175 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+175 added−3 removed
- tests:+73 added−1 removed
- other:+102 added−2 removed
Provenance
- Commit
45a2977- Tree
a6983f8- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d6f4818- Parent 2
c121b98
4 files changed+175 added−3 removed
modified:requests/structures.py+89 added
6 unmodified lines7 Data structures that power Requests.8 """9 10 import collections11+import time12 13 from .compat import OrderedDict14 15+current_time = getattr(time, 'monotonic', time.time)16 17+18 class CaseInsensitiveDict(collections.MutableMapping):19 """A case-insensitive ``dict``-like object.20 21 Implements all methods and operations of83 unmodified lines105 return self.__dict__.get(key, None)106 107 def get(self, key, default=None):108 return self.__dict__.get(key, default)109+110+111+class TimedCacheManaged(object):112+ """113+ Wrap a function call in a timed cache114+ """115+ def __init__(self, fnc):116+ self.fnc = fnc117+ self.cache = TimedCache()118+119+ def __call__(self, *args, **kwargs):120+ key = args[0]121+ found = None122+ try:123+ found = self.cache[key]124+ except KeyError:125+ found = self.fnc(key, **kwargs)126+ self.cache[key] = found127+128+ return found129+130+131+class TimedCache(collections.MutableMapping):132+ """133+ Evicts entries after expiration_secs. If none are expired and maxlen is hit,134+ will evict the oldest cached entry135+ """136+ def __init__(self, maxlen=32, expiration_secs=60):137+ """138+ :param maxlen: most number of entries to hold on to139+ :param expiration_secs: the number of seconds to hold on140+ to entries141+ """142+ self.maxlen = maxlen143+ self.expiration_secs = expiration_secs144+ self._dict = OrderedDict()145+146+ def __repr__(self):147+ return '<TimedCache maxlen:%d len:%d expiration_secs:%d>' % \148+ (self.maxlen, len(self._dict), self.expiration_secs)149+150+ def __iter__(self):151+ return map(lambda kv: (kv[0], kv[1][1]), self._dict.items()).__iter__()152+153+ def __delitem__(self, item):154+ return self._dict.__delitem__(item)155+156+ def __getitem__(self, key):157+ """158+ Look up an item in the cache. If the item159+ has already expired, it will be invalidated and not returned160+161+ :param key: which entry to look up162+ :return: the value in the cache, or None163+ """164+ occurred, value = self._dict[key]165+ now = int(current_time())166+167+ if now - occurred > self.expiration_secs:168+ del self._dict[key]169+ raise KeyError170+ else:171+ return value172+173+ def __setitem__(self, key, value):174+ """175+ Locates the value at lookup key, if cache is full, will evict the176+ oldest entry177+178+ :param key: the key to search the cache for179+ :param value: the value to be added to the cache180+ """181+ now = int(current_time())182+183+ while len(self._dict) >= self.maxlen:184+ self._dict.popitem(last=False)185+186+ return self._dict.__setitem__(key, (now, value))187+188+ def __len__(self):189+ """:return: the length of the cache"""190+ return len(self._dict)191+192+ def clear(self):193+ """Clears the cache"""194+ return self._dict.clear()modified:requests/utils.py+12 added-2 removed
26 unmodified lines27 from .compat import (28 quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,29 proxy_bypass, urlunparse, basestring, integer_types)30 from .cookies import RequestsCookieJar, cookiejar_from_dict31-from .structures import CaseInsensitiveDict31+from .structures import CaseInsensitiveDict, TimedCache, TimedCacheManaged32 from .exceptions import (33 InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)34 35 _hush_pyflakes = (RequestsCookieJar,)542 unmodified lines578 else:579 os.environ[env_name] = old_value580 581 582+@TimedCacheManaged583+def _proxy_bypass_cached(netloc):584+ """585+ Looks for netloc in the cache, if not found, will call proxy_bypass586+ for the netloc and store its result in the cache587+588+ :rtype: bool589+ """590+ return proxy_bypass(netloc)591+592 def should_bypass_proxies(url, no_proxy):593 """594 Returns whether we should bypass proxies or not.595 39 unmodified lines635 # exceptions we've seen, though: this call failing in other ways can reveal636 # legitimate problems.637 with set_environ('no_proxy', no_proxy_arg):638 try:629- bypass = proxy_bypass(netloc)639+ bypass = _proxy_bypass_cached(netloc)640 except (TypeError, socket.gaierror):641 bypass = False642 643 if bypass:222 unmodified linesmodified:tests/test_structures.py+73 added-1 removed
1 # -*- coding: utf-8 -*-2 3 import pytest4 5-from requests.structures import CaseInsensitiveDict, LookupDict5+from requests.structures import CaseInsensitiveDict, LookupDict, TimedCache, TimedCacheManaged6 7 8 class TestCaseInsensitiveDict:9 63 unmodified lines73 74 @get_item_parameters75 def test_get(self, key, value):76 assert self.lookup_dict.get(key) == value77+78+79+class TestTimedCache(object):80+ @pytest.fixture(autouse=True)81+ def setup(self):82+ self.any_value = 'some value'83+ self.expiration_secs = 6084+ self.cache = TimedCache(expiration_secs=self.expiration_secs)85+ yield86+ self.cache.clear()87+88+ def test_get(self):89+ self.cache['a'] = self.any_value90+ assert self.cache['a'] is self.any_value91+92+ def test_repr(self):93+ repr = str(self.cache)94+ assert repr == '<TimedCache maxlen:32 len:0 expiration_secs:60>'95+96+ def test_get_expired_item(self, mocker):97+ self.cache = TimedCache(maxlen=1, expiration_secs=self.expiration_secs)98+99+ mocker.patch('requests.structures.current_time', lambda: 0)100+ self.cache['a'] = self.any_value101+ mocker.patch('requests.structures.current_time', lambda: self.expiration_secs + 1)102+ assert self.cache.get('a') is None103+104+ def test_evict_first_entry_when_full(self, mocker):105+ self.cache = TimedCache(maxlen=2, expiration_secs=2)106+ mocker.patch('requests.structures.current_time', lambda: 0)107+ self.cache['a'] = self.any_value108+ mocker.patch('requests.structures.current_time', lambda: 1)109+ self.cache['b'] = self.any_value110+ mocker.patch('requests.structures.current_time', lambda: 3)111+ self.cache['c'] = self.any_value112+ assert len(self.cache) is 2113+ with pytest.raises(KeyError, message='Expected key not found'):114+ self.cache['a']115+ assert self.cache['b'] is self.any_value116+ assert self.cache['c'] is self.any_value117+118+ def test_delete_item_removes_item(self):119+ self.cache['a'] = self.any_value120+ del self.cache['a']121+ with pytest.raises(KeyError, message='Expected key not found'):122+ self.cache['a']123+124+ def test_iterating_hides_timestamps(self):125+ self.cache['a'] = 1126+ self.cache['b'] = 2127+ expected = [('a', 1), ('b', 2)]128+ actual = [(key, val) for key, val in self.cache]129+ assert expected == actual130+131+132+class TestTimedCacheManagedDecorator(object):133+ def test_caches_repeated_calls(self, mocker):134+ mocker.patch('requests.structures.current_time', lambda: 0)135+136+ nonlocals = {'value': 0}137+138+ @TimedCacheManaged139+ def some_method(x):140+ nonlocals['value'] = nonlocals['value'] + x141+ return nonlocals['value']142+143+ first_result = some_method(1)144+ assert first_result is 1145+ second_result = some_method(1)146+ assert second_result is 1147+ third_result = some_method(2)148+ assert third_result is 3modified:AUTHORS.rst+1 added
176 unmodified lines177 - Andrii Soldatenko (`@a_soldatenko <https://github.com/andriisoldatenko>`_)178 - Moinuddin Quadri <moin18@gmail.com> (`@moin18 <https://github.com/moin18>`_)179 - Matt Kohl (`@mattkohl <https://github.com/mattkohl>`_)180 - Jonathan Vanasco (`@jvanasco <https://github.com/jvanasco>`_)181+- David Fontenot (`@davidfontenot <https://github.com/davidfontenot>`_)182