1
- import json
2
1
import logging
3
- from datetime import datetime
4
- from pathlib import Path
5
- from typing import Generator , Optional , Tuple , Type , Callable , Union
2
+ from typing import Generator , Optional
6
3
7
4
import dateutil .parser
8
5
import httpx
9
- from platformdirs import user_cache_dir
10
6
11
7
from ..config import API_KEY , CONFIG , APIKey
12
8
from . import USER_AGENT , RetryableHTTPClient , encode_json
13
- from .cache import CachedToken
14
-
9
+ from .cache import ACCESS_TOKEN_CACHE_CLS_TYPE , FileCachedToken , get_access_token_cache_cache
15
10
logger = logging .getLogger (__name__ )
16
11
17
12
18
- class FileCachedToken (CachedToken ):
19
- def __init__ (self ):
20
- self ._cache_file = Path (user_cache_dir ("syncsparkpy" )) / "auth.json"
21
-
22
- super ().__init__ ()
23
-
24
- def _get_cached_token (self ) -> Optional [Tuple [str , datetime ]]:
25
- # Cache is optional, we can fail to read it and not worry
26
- if self ._cache_file .exists ():
27
- try :
28
- cached_token = json .loads (self ._cache_file .read_text ())
29
- cached_access_token = cached_token ["access_token" ]
30
- cached_expiry = datetime .fromisoformat (cached_token ["expires_at_utc" ])
31
- return cached_access_token , cached_expiry
32
- except Exception as e :
33
- logger .warning (
34
- f"Failed to read cached access token @ { self ._cache_file } " , exc_info = e
35
- )
36
-
37
- return None
38
-
39
- def _set_cached_token (self ) -> None :
40
- # Cache is optional, we can fail to read it and not worry
41
- try :
42
- self ._cache_file .parent .mkdir (parents = True , exist_ok = True )
43
- self ._cache_file .write_text (
44
- json .dumps (
45
- {
46
- "access_token" : self ._access_token ,
47
- "expires_at_utc" : self ._access_token_expires_at_utc .isoformat (),
48
- }
49
- )
50
- )
51
- except Exception as e :
52
- logger .warning (
53
- f"Failed to write cached access token @ { self ._cache_file } " , exc_info = e
54
- )
55
-
56
-
57
- # Putting this here instead of config.py because circular imports and typing.
58
- _access_token_cache_cls = FileCachedToken # Default to local file caching.
59
- ACCESS_TOKEN_CACHE_CLS_TYPE = Union [Type [CachedToken ], Callable [[], CachedToken ]]
60
-
61
-
62
- def set_access_token_cache_cls (access_token_cache_cls : ACCESS_TOKEN_CACHE_CLS_TYPE ) -> None :
63
- global _access_token_cache_cls
64
- _access_token_cache_cls = access_token_cache_cls
65
-
66
-
67
13
class SyncAuth (httpx .Auth ):
68
14
requires_response_body = True
69
15
@@ -395,7 +341,7 @@ def get_default_client() -> SyncClient:
395
341
_sync_client = SyncClient (
396
342
CONFIG .api_url ,
397
343
API_KEY ,
398
- access_token_cache_cls = _access_token_cache_cls
344
+ access_token_cache_cls = get_access_token_cache_cache ()
399
345
)
400
346
return _sync_client
401
347
@@ -409,6 +355,6 @@ def get_default_async_client() -> ASyncClient:
409
355
_async_sync_client = ASyncClient (
410
356
CONFIG .api_url ,
411
357
API_KEY ,
412
- access_token_cache_cls = _access_token_cache_cls
358
+ access_token_cache_cls = get_access_token_cache_cache ()
413
359
)
414
360
return _async_sync_client
0 commit comments