|
| 1 | +import os |
1 | 2 | from functools import lru_cache |
2 | 3 | from io import BytesIO |
3 | | -from typing import TYPE_CHECKING, Any, Final, Generic, Type, TypeVar |
| 4 | +from typing import TYPE_CHECKING, Any, ClassVar, Final, Generic, Type, TypeVar |
4 | 5 |
|
5 | 6 | import requests |
6 | 7 | from requests import codes |
@@ -28,13 +29,37 @@ class BaseService(Generic[BaseResponseT]): |
28 | 29 | """ |
29 | 30 | __base_url: Final[str] = "https://{subdomain}.abstractapi.com/v1/" |
30 | 31 | _subdomain: str |
| 32 | + _service_name_env_var: ClassVar[str] |
31 | 33 |
|
32 | | - def __init__(self, api_key: str) -> None: |
| 34 | + @classmethod |
| 35 | + def _read_api_key_from_env(cls) -> str | None: |
| 36 | + """Reads service API key from environment variables. |
| 37 | +
|
| 38 | + API key exposed as an environment variable must be exposed using a |
| 39 | + variable name with the pattern: |
| 40 | + ABSTRACTAPI_{SERVICE_NAME}_API_KEY |
| 41 | + Where SERVICE_NAME is the service name that the API key is for. |
| 42 | + (service_name must be uppercase.) |
| 43 | +
|
| 44 | + Returns: API key read from environment variable. |
| 45 | + """ |
| 46 | + pattern = "ABSTRACTAPI_{service_name}_API_KEY" |
| 47 | + return os.environ.get( |
| 48 | + pattern.format(service_name=cls._service_name_env_var) |
| 49 | + ) |
| 50 | + |
| 51 | + def __init__(self, api_key: str | None = None) -> None: |
33 | 52 | """Constructs a BaseService. |
34 | 53 |
|
35 | 54 | Args: |
36 | 55 | api_key: API key to be used to authenticate with AbstractAPI. |
37 | 56 | """ |
| 57 | + api_key = api_key or self._read_api_key_from_env() |
| 58 | + if api_key is None: |
| 59 | + raise ValueError( |
| 60 | + "API key was not provided nor exposed as an" |
| 61 | + " environment variable" |
| 62 | + ) |
38 | 63 | self._api_key: str = api_key |
39 | 64 |
|
40 | 65 | @lru_cache(maxsize=5) |
|
0 commit comments