-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
58 lines (49 loc) · 1.62 KB
/
Copy pathclient.py
File metadata and controls
58 lines (49 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import datetime
import os
import pickle
import yahoo_fantasy_api as yfa
from yahoo_oauth import OAuth2
CACHE_FILE = '.yahoo_cache.pkl'
def get_league(oauth_file=None, cache=False):
if oauth_file is None:
oauth_file = os.environ.get('YAHOO_OAUTH_FILE', 'oauth2.json')
sc = OAuth2(None, None, from_file=oauth_file)
gm = yfa.Game(sc, 'mlb')
ids = gm.league_ids(game_codes=['mlb'])
if not ids:
raise RuntimeError('No MLB leagues found')
current_year = str(datetime.date.today().year)
current_id = None
for lid in ids:
try:
candidate = gm.to_league(lid)
if str(candidate.settings().get('season')) == current_year:
current_id = lid
break
except Exception:
pass
if current_id is None:
raise RuntimeError(f'No MLB league found for {current_year}')
lg = gm.to_league(current_id)
if cache:
_patch_cache(lg.yhandler)
return lg
def _patch_cache(yhandler):
"""Wrap yhandler.get() to cache responses keyed by URI."""
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, 'rb') as f:
store = pickle.load(f)
else:
store = {}
original_get = yhandler.get.__func__ # unbound method
def cached_get(self, uri):
if uri in store:
print(f' [cache] {uri[:80]}', flush=True)
return store[uri]
result = original_get(self, uri)
store[uri] = result
with open(CACHE_FILE, 'wb') as f:
pickle.dump(store, f)
return result
import types
yhandler.get = types.MethodType(cached_get, yhandler)