Skip to content

Commit

Permalink
Merge pull request #1930 from ranaroussi/fix/session-switching
Browse files Browse the repository at this point in the history
Fix switching session from/to requests_cache
  • Loading branch information
ValueRaider authored May 11, 2024
2 parents 070f135 + ac4efa3 commit 7c41434
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions yfinance/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,24 +60,8 @@ class YfData(metaclass=SingletonMeta):
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

def __init__(self, session=None):
self._session = session or requests.Session()

try:
self._session.cache
except AttributeError:
# Not caching
self._session_is_caching = False
else:
# Is caching. This is annoying.
# Can't simply use a non-caching session to fetch cookie & crumb,
# because then the caching-session won't have cookie.
self._session_is_caching = True
from requests_cache import DO_NOT_CACHE
self._expire_after = DO_NOT_CACHE
self._crumb = None
self._cookie = None
if self._session_is_caching and self._cookie is None:
utils.print_once("WARNING: cookie & crumb does not work well with requests_cache. Am experimenting with 'expire_after=DO_NOT_CACHE', but you need to help stress-test.")

# Default to using 'basic' strategy
self._cookie_strategy = 'basic'
Expand All @@ -86,12 +70,27 @@ def __init__(self, session=None):

self._cookie_lock = threading.Lock()

self._set_session(session or requests.Session())

def _set_session(self, session):
if session is None:
return
with self._cookie_lock:
self._session = session

try:
self._session.cache
except AttributeError:
# Not caching
self._session_is_caching = False
else:
# Is caching. This is annoying.
# Can't simply use a non-caching session to fetch cookie & crumb,
# because then the caching-session won't have cookie.
self._session_is_caching = True
from requests_cache import DO_NOT_CACHE
self._expire_after = DO_NOT_CACHE

def _set_cookie_strategy(self, strategy, have_lock=False):
if strategy == self._cookie_strategy:
return
Expand Down

0 comments on commit 7c41434

Please sign in to comment.