66import httpx
77
88from obelisk .exceptions import AuthenticationError
9- from obelisk .strategies .retry import RetryStrategy , \
10- NoRetryStrategy
9+ from obelisk .strategies .retry import RetryStrategy , NoRetryStrategy
1110from obelisk .types import ObeliskKind
1211
1312
@@ -32,27 +31,33 @@ class BaseClient:
3231
3332 log : logging .Logger
3433
35- def __init__ (self , client : str , secret : str ,
36- retry_strategy : RetryStrategy = NoRetryStrategy (),
37- kind : ObeliskKind = ObeliskKind .CLASSIC ) -> None :
34+ def __init__ (
35+ self ,
36+ client : str ,
37+ secret : str ,
38+ retry_strategy : RetryStrategy = NoRetryStrategy (),
39+ kind : ObeliskKind = ObeliskKind .CLASSIC ,
40+ ) -> None :
3841 self ._client = client
3942 self ._secret = secret
4043 self .retry_strategy = retry_strategy
4144 self .kind = kind
4245
43- self .log = logging .getLogger (' obelisk' )
46+ self .log = logging .getLogger (" obelisk" )
4447
4548 async def _get_token (self ):
46- auth_string = str (base64 .b64encode (
47- f'{ self ._client } :{ self ._secret } ' .encode ('utf-8' )), 'utf-8' )
49+ auth_string = str (
50+ base64 .b64encode (f"{ self ._client } :{ self ._secret } " .encode ("utf-8" )), "utf-8"
51+ )
4852 headers = {
49- ' Authorization' : f' Basic { auth_string } ' ,
50- ' Content-Type' : ('application/json'
51- if self . kind . use_json_auth else ' application/x-www-form-urlencoded' )
52- }
53- payload = {
54- 'grant_type' : 'client_credentials'
53+ " Authorization" : f" Basic { auth_string } " ,
54+ " Content-Type" : (
55+ " application/json"
56+ if self . kind . use_json_auth
57+ else "application/x-www-form-urlencoded"
58+ ),
5559 }
60+ payload = {"grant_type" : "client_credentials" }
5661
5762 async with httpx .AsyncClient () as client :
5863 response = None
@@ -64,7 +69,8 @@ async def _get_token(self):
6469 self .kind .token_url ,
6570 json = payload if self .kind .use_json_auth else None ,
6671 data = payload if not self .kind .use_json_auth else None ,
67- headers = headers )
72+ headers = headers ,
73+ )
6874
6975 response = request .json ()
7076 except Exception as e :
@@ -76,30 +82,33 @@ async def _get_token(self):
7682 raise last_error
7783
7884 if request .status_code != 200 :
79- if ' error' in response :
85+ if " error" in response :
8086 self .log .warning (f"Could not authenticate, { response ['error' ]} " )
8187 raise AuthenticationError
8288
83- self ._token = response ['access_token' ]
84- self ._token_expires = (datetime .now ()
85- + timedelta (seconds = response ['expires_in' ]))
89+ self ._token = response ["access_token" ]
90+ self ._token_expires = datetime .now () + timedelta (
91+ seconds = response ["expires_in" ]
92+ )
8693
8794 async def _verify_token (self ):
88- if (self ._token is None
89- or self ._token_expires < (datetime .now () - self .grace_period )):
95+ if self ._token is None or self ._token_expires < (
96+ datetime .now () - self .grace_period
97+ ):
9098 retry = self .retry_strategy .make ()
9199 first = True
92100 while first or await retry .should_retry ():
93101 first = False
94102 try :
95103 await self ._get_token ()
96104 return
97- except : # noqa: E722
105+ except : # noqa: E722
98106 self .log .info ("excepted, Retrying token fetch" )
99107 continue
100108
101- async def http_post (self , url : str , data : Any = None ,
102- params : Optional [dict ] = None ) -> httpx .Response :
109+ async def http_post (
110+ self , url : str , data : Any = None , params : Optional [dict ] = None
111+ ) -> httpx .Response :
103112 """
104113 Send an HTTP POST request to Obelisk,
105114 with proper auth.
@@ -114,8 +123,8 @@ async def http_post(self, url: str, data: Any = None,
114123 await self ._verify_token ()
115124
116125 headers = {
117- ' Authorization' : f' Bearer { self ._token } ' ,
118- ' Content-Type' : ' application/json'
126+ " Authorization" : f" Bearer { self ._token } " ,
127+ " Content-Type" : " application/json" ,
119128 }
120129 if params is None :
121130 params = {}
@@ -128,11 +137,12 @@ async def http_post(self, url: str, data: Any = None,
128137 self .log .debug (f"Retrying, last response: { response .status_code } " )
129138
130139 try :
131- response = await client .post (url ,
132- json = data ,
133- params = {k : v for k , v in params .items () if
134- v is not None },
135- headers = headers )
140+ response = await client .post (
141+ url ,
142+ json = data ,
143+ params = {k : v for k , v in params .items () if v is not None },
144+ headers = headers ,
145+ )
136146
137147 if response .status_code // 100 == 2 :
138148 return response
@@ -145,7 +155,6 @@ async def http_post(self, url: str, data: Any = None,
145155 raise last_error
146156 return response
147157
148-
149158 async def http_get (self , url : str , params : Optional [dict ] = None ) -> httpx .Response :
150159 """
151160 Send an HTTP GET request to Obelisk,
@@ -161,8 +170,8 @@ async def http_get(self, url: str, params: Optional[dict] = None) -> httpx.Respo
161170 await self ._verify_token ()
162171
163172 headers = {
164- ' Authorization' : f' Bearer { self ._token } ' ,
165- ' Content-Type' : ' application/json'
173+ " Authorization" : f" Bearer { self ._token } " ,
174+ " Content-Type" : " application/json" ,
166175 }
167176 if params is None :
168177 params = {}
@@ -175,10 +184,11 @@ async def http_get(self, url: str, params: Optional[dict] = None) -> httpx.Respo
175184 self .log .debug (f"Retrying, last response: { response .status_code } " )
176185
177186 try :
178- response = await client .get (url ,
179- params = {k : v for k , v in params .items () if
180- v is not None },
181- headers = headers )
187+ response = await client .get (
188+ url ,
189+ params = {k : v for k , v in params .items () if v is not None },
190+ headers = headers ,
191+ )
182192
183193 if response .status_code // 100 == 2 :
184194 return response
0 commit comments