|
1 | 1 | import logging |
2 | 2 | from typing import Any, Dict, List, Optional, Union |
| 3 | +from oauthlib.oauth2 import TokenExpiredError |
3 | 4 |
|
4 | 5 | from Newmode import Client |
5 | 6 |
|
@@ -429,7 +430,10 @@ def __init__( |
429 | 430 | self.client_id: str = check_env.check("NEWMODE_API_CLIENT_ID", client_id) |
430 | 431 | self.client_secret: str = check_env.check("NEWMODE_API_CLIENT_SECRET", client_secret) |
431 | 432 | self.headers: Dict[str, str] = {"content-type": "application/json"} |
432 | | - self.default_client: OAuth2APIConnector = OAuth2APIConnector( |
| 433 | + self.default_client: OAuth2APIConnector = self.get_default_oauth_client() |
| 434 | + |
| 435 | + def get_default_oauth_client(self) -> OAuth2APIConnector: |
| 436 | + return OAuth2APIConnector( |
433 | 437 | uri=self.base_url, |
434 | 438 | auto_refresh_url=V2_API_AUTH_URL, |
435 | 439 | client_id=self.client_id, |
@@ -472,10 +476,14 @@ def base_request( |
472 | 476 |
|
473 | 477 | for attempt in range(retries + 1): |
474 | 478 | try: |
475 | | - response = client.request( |
476 | | - url=url, req_type=method, json=json, data=data, params=params |
477 | | - ) |
478 | | - return self.checked_response(response, client) |
| 479 | + try: |
| 480 | + response = client.request( |
| 481 | + url=url, req_type=method, json=json, data=data, params=params |
| 482 | + ) |
| 483 | + return self.checked_response(response, client) |
| 484 | + except TokenExpiredError as e: |
| 485 | + logger.warning(f"Token expired: {e}. Refreshing it...") |
| 486 | + self.default_client = self.get_default_oauth_client() |
479 | 487 | except Exception as e: |
480 | 488 | if attempt < retries: |
481 | 489 | logger.warning(f"Request failed (attempt {attempt + 1}/{retries}). Retrying...") |
|
0 commit comments