Skip to content

Commit 6475110

Browse files
authored
chore: linting and typing (#233)
* fix: Use a (slightly) better way of getting UTC+Zulu timestamps. * chore: add some typing, adjust some code to make pylint and pyright happier.
1 parent 218e632 commit 6475110

File tree

4 files changed

+52
-32
lines changed

4 files changed

+52
-32
lines changed

src/sumo/wrapper/_auth_provider.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import time
88
from datetime import datetime, timedelta, timezone
99
from pathlib import Path
10+
from typing import Dict
1011
from urllib.parse import parse_qs
1112

1213
import jwt
@@ -76,10 +77,10 @@ def get_token(self):
7677
# ELSE
7778
return result["access_token"]
7879

79-
def get_authorization(self):
80+
def get_authorization(self) -> Dict:
8081
token = self.get_token()
8182
if token is None:
82-
return ""
83+
return {}
8384

8485
return {"Authorization": "Bearer " + token}
8586

@@ -101,6 +102,13 @@ def has_case_token(self, case_uuid):
101102
pass
102103

103104

105+
class AuthProviderNone(AuthProvider):
106+
def get_token(self):
107+
raise Exception("No valid authorization provider found.")
108+
109+
pass
110+
111+
104112
class AuthProviderSilent(AuthProvider):
105113
def __init__(self, client_id, authority, resource_id):
106114
super().__init__(resource_id)
@@ -423,7 +431,7 @@ def get_auth_provider(
423431
refresh_token=None,
424432
devicecode=False,
425433
case_uuid=None,
426-
):
434+
) -> AuthProvider:
427435
if refresh_token:
428436
return AuthProviderRefreshToken(
429437
refresh_token, client_id, authority, resource_id
@@ -472,6 +480,8 @@ def get_auth_provider(
472480
]
473481
):
474482
return AuthProviderManaged(resource_id)
483+
# ELSE
484+
return AuthProviderNone(resource_id)
475485

476486

477487
def cleanup_shared_keys():
@@ -481,7 +491,7 @@ def cleanup_shared_keys():
481491
for f in os.listdir(tokendir):
482492
ff = os.path.join(tokendir, f)
483493
if os.path.isfile(ff):
484-
(name, ext) = os.path.splitext(ff)
494+
(_, ext) = os.path.splitext(ff)
485495
if ext.lower() == ".sharedkey":
486496
try:
487497
with open(ff, "r") as file:

src/sumo/wrapper/_logging.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import logging
2-
from datetime import datetime
2+
from datetime import datetime, timezone
33

44

55
class LogHandlerSumo(logging.Handler):
@@ -11,8 +11,8 @@ def __init__(self, sumo_client):
1111
def emit(self, record):
1212
try:
1313
dt = (
14-
datetime.now(datetime.timezone.utc)
15-
.replace(microsecond=0)
14+
datetime.now(timezone.utc)
15+
.replace(microsecond=0, tzinfo=None)
1616
.isoformat()
1717
+ "Z"
1818
)

src/sumo/wrapper/_retry_strategy.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def __init__(self, stop_after=6, multiplier=0.5, exp_base=2):
4444
self._exp_base = exp_base
4545
return
4646

47-
def make_retryer(self):
47+
def make_retryer(self) -> tn.Retrying:
4848
return tn.Retrying(
4949
stop=tn.stop_after_attempt(self._stop_after),
5050
retry=(
@@ -63,7 +63,7 @@ def make_retryer(self):
6363
before_sleep=_log_retry_info,
6464
)
6565

66-
def make_retryer_async(self):
66+
def make_retryer_async(self) -> tn.AsyncRetrying:
6767
return tn.AsyncRetrying(
6868
stop=tn.stop_after_attempt(self._stop_after),
6969
retry=(

src/sumo/wrapper/sumo_client.py

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
import re
55
import time
6+
from typing import Dict, Optional, Tuple
67

78
import httpx
89
import jwt
@@ -25,10 +26,13 @@
2526
class SumoClient:
2627
"""Authenticate and perform requests to the Sumo API."""
2728

29+
_client: httpx.Client
30+
_async_client: httpx.AsyncClient
31+
2832
def __init__(
2933
self,
3034
env: str,
31-
token: str = None,
35+
token: Optional[str] = None,
3236
interactive: bool = False,
3337
devicecode: bool = False,
3438
verbosity: str = "CRITICAL",
@@ -119,26 +123,23 @@ def __init__(
119123
def __enter__(self):
120124
return self
121125

122-
def __exit__(self, exc_type, exc_value, traceback):
126+
def __exit__(self, *_):
123127
if not self._borrowed_client:
124128
self._client.close()
125-
self._client = None
126129
return False
127130

128131
async def __aenter__(self):
129132
return self
130133

131-
async def __aexit__(self, exc_type, exc_value, traceback):
134+
async def __aexit__(self, *_):
132135
if not self._borrowed_async_client:
133136
await self._async_client.aclose()
134-
self._async_client = None
135137
return False
136138

137139
def __del__(self):
138140
if self._client is not None and not self._borrowed_client:
139141
self._client.close()
140142
pass
141-
self._client = None
142143
if self._async_client is not None and not self._borrowed_async_client:
143144

144145
async def closeit(client):
@@ -151,7 +152,6 @@ async def closeit(client):
151152
except RuntimeError:
152153
pass
153154
pass
154-
self._async_client = None
155155

156156
def authenticate(self):
157157
if self.auth is None:
@@ -186,7 +186,7 @@ def blob_client(self) -> BlobClient:
186186
)
187187

188188
@raise_for_status
189-
def get(self, path: str, params: dict = None) -> dict:
189+
def get(self, path: str, params: Optional[Dict] = None) -> httpx.Response:
190190
"""Performs a GET-request to the Sumo API.
191191
192192
Args:
@@ -247,9 +247,9 @@ def _get():
247247
def post(
248248
self,
249249
path: str,
250-
blob: bytes = None,
251-
json: dict = None,
252-
params: dict = None,
250+
blob: Optional[bytes] = None,
251+
json: Optional[dict] = None,
252+
params: Optional[dict] = None,
253253
) -> httpx.Response:
254254
"""Performs a POST-request to the Sumo API.
255255
@@ -320,7 +320,10 @@ def _post():
320320

321321
@raise_for_status
322322
def put(
323-
self, path: str, blob: bytes = None, json: dict = None
323+
self,
324+
path: str,
325+
blob: Optional[bytes] = None,
326+
json: Optional[dict] = None,
324327
) -> httpx.Response:
325328
"""Performs a PUT-request to the Sumo API.
326329
@@ -365,7 +368,9 @@ def _put():
365368
return retryer(_put)
366369

367370
@raise_for_status
368-
def delete(self, path: str, params: dict = None) -> dict:
371+
def delete(
372+
self, path: str, params: Optional[dict] = None
373+
) -> httpx.Response:
369374
"""Performs a DELETE-request to the Sumo API.
370375
371376
Args:
@@ -402,12 +407,12 @@ def _delete():
402407

403408
return retryer(_delete)
404409

405-
def _get_retry_details(self, response_in):
410+
def _get_retry_details(self, response_in) -> Tuple[str, int]:
406411
assert response_in.status_code == 202, (
407412
"Incorrect status code; expcted 202"
408413
)
409414
headers = response_in.headers
410-
location = headers.get("location")
415+
location: str = headers.get("location")
411416
assert location is not None, "Missing header: Location"
412417
assert location.startswith(self.base_url)
413418
retry_after = headers.get("retry-after")
@@ -440,7 +445,6 @@ def poll(
440445
)
441446
location, retry_after = self._get_retry_details(response)
442447
pass
443-
return None # should never get here.
444448

445449
def getLogger(self, name):
446450
"""Gets a logger object that sends log objects into the message_log
@@ -495,7 +499,9 @@ def client_for_case(self, case_uuid):
495499
return self
496500

497501
@raise_for_status_async
498-
async def get_async(self, path: str, params: dict = None):
502+
async def get_async(
503+
self, path: str, params: Optional[dict] = None
504+
) -> httpx.Response:
499505
"""Performs an async GET-request to the Sumo API.
500506
501507
Args:
@@ -556,9 +562,9 @@ async def _get():
556562
async def post_async(
557563
self,
558564
path: str,
559-
blob: bytes = None,
560-
json: dict = None,
561-
params: dict = None,
565+
blob: Optional[bytes] = None,
566+
json: Optional[dict] = None,
567+
params: Optional[dict] = None,
562568
) -> httpx.Response:
563569
"""Performs an async POST-request to the Sumo API.
564570
@@ -630,7 +636,10 @@ async def _post():
630636

631637
@raise_for_status_async
632638
async def put_async(
633-
self, path: str, blob: bytes = None, json: dict = None
639+
self,
640+
path: str,
641+
blob: Optional[bytes] = None,
642+
json: Optional[dict] = None,
634643
) -> httpx.Response:
635644
"""Performs an async PUT-request to the Sumo API.
636645
@@ -675,7 +684,9 @@ async def _put():
675684
return await retryer(_put)
676685

677686
@raise_for_status_async
678-
async def delete_async(self, path: str, params: dict = None) -> dict:
687+
async def delete_async(
688+
self, path: str, params: Optional[dict] = None
689+
) -> httpx.Response:
679690
"""Performs an async DELETE-request to the Sumo API.
680691
681692
Args:
@@ -736,4 +747,3 @@ async def poll_async(
736747
)
737748
location, retry_after = self._get_retry_details(response)
738749
pass
739-
return None # should never get here.

0 commit comments

Comments
 (0)