|
| 1 | +"""Utilities for working with the project's constants.""" |
| 2 | +import logging |
| 3 | +import typing |
| 4 | +from collections.abc import Sequence |
| 5 | + |
| 6 | +import pydantic |
| 7 | +from pydantic.error_wrappers import ErrorWrapper |
| 8 | + |
| 9 | +logger = logging.getLogger("cjms.settings") |
| 10 | + |
| 11 | +# This is available in pydantic as pydantic.error_wrappers.ErrorList |
| 12 | +# but is typehinted as a Sequence[any], due to being a recursive type. |
| 13 | +# This makes it harder to handle the types. |
| 14 | +# For our purposes, a fully accurate representation is not necessary. |
| 15 | +_PYDANTIC_ERROR_TYPE = Sequence[ErrorWrapper | Sequence[ErrorWrapper]] |
| 16 | + |
| 17 | + |
| 18 | +class CJMSBaseSettings(pydantic.BaseSettings): |
| 19 | + """Base class for settings with .env support and nicer error messages.""" |
| 20 | + |
| 21 | + @staticmethod |
| 22 | + def __log_missing_errors(base_error: pydantic.ValidationError, errors: _PYDANTIC_ERROR_TYPE) -> bool: |
| 23 | + """ |
| 24 | + Log out a nice representation for missing environment variables. |
| 25 | +
|
| 26 | + Returns false if none of the errors were caused by missing variables. |
| 27 | + """ |
| 28 | + found_relevant_errors = False |
| 29 | + for error in errors: |
| 30 | + if isinstance(error, Sequence): |
| 31 | + found_relevant_errors = ( |
| 32 | + CJMSBaseSettings.__log_missing_errors(base_error, error) or found_relevant_errors |
| 33 | + ) |
| 34 | + elif isinstance(error.exc, pydantic.MissingError): |
| 35 | + logger.error(f"Missing environment variable {base_error.args[1].__name__}.{error.loc_tuple()[0]}") |
| 36 | + found_relevant_errors = True |
| 37 | + |
| 38 | + return found_relevant_errors |
| 39 | + |
| 40 | + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: |
| 41 | + """Try to instantiate the class, and print a nicer message for unset variables.""" |
| 42 | + try: |
| 43 | + super().__init__(*args, **kwargs) |
| 44 | + except pydantic.ValidationError as error: |
| 45 | + if CJMSBaseSettings.__log_missing_errors(error, error.raw_errors): |
| 46 | + exit(1) |
| 47 | + else: |
| 48 | + # The validation error is not due to an unset environment variable, propagate the error as normal |
| 49 | + raise error from None |
| 50 | + |
| 51 | + class Config: |
| 52 | + """Enable env files.""" |
| 53 | + |
| 54 | + frozen = True |
| 55 | + |
| 56 | + env_file = ".env" |
| 57 | + env_file_encoding = "utf-8" |
0 commit comments