-
Notifications
You must be signed in to change notification settings - Fork 20
/
settings.py
66 lines (48 loc) · 1.99 KB
/
settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from __future__ import annotations
__all__ = (
"SqlalchemyDsn",
"LocalFileUrl",
"ServiceSettingsBase",
)
import contextlib
from pathlib import Path
from typing import TYPE_CHECKING, Any, AsyncIterator, Self, TypeVar
from authlib.jose import JsonWebKey
from pydantic import AnyUrl, BaseSettings, SecretStr, parse_obj_as
if TYPE_CHECKING:
from pydantic.config import BaseConfig
from pydantic.fields import ModelField
T = TypeVar("T")
class SqlalchemyDsn(AnyUrl):
allowed_schemes = {"sqlite+aiosqlite", "mysql+aiomysql"}
class TokenSigningKey(SecretStr):
jwk: JsonWebKey
def __init__(self, data: str):
super().__init__(data)
self.jwk = JsonWebKey.import_key(self.get_secret_value())
@classmethod
# TODO: This should return TokenSigningKey but pydantic's type hints are wrong
def validate(cls, value: Any) -> SecretStr:
"""Load private keys from files if needed"""
if isinstance(value, str) and not value.strip().startswith("-----BEGIN"):
url = parse_obj_as(LocalFileUrl, value)
value = Path(url.path).read_text()
return super().validate(value)
class LocalFileUrl(AnyUrl):
host_required = False
allowed_schemes = {"file"}
@classmethod
# TODO: This should return LocalFileUrl but pydantic's type hints are wrong
def validate(cls, value: Any, field: ModelField, config: BaseConfig) -> AnyUrl:
"""Overrides AnyUrl.validate to add file:// scheme if not present."""
if isinstance(value, str) and "://" not in value:
value = f"file://{value}"
return super().validate(value, field, config)
class ServiceSettingsBase(BaseSettings, allow_mutation=False):
@classmethod
def create(cls) -> Self:
raise NotImplementedError("This should never be called")
@contextlib.asynccontextmanager
async def lifetime_function(self) -> AsyncIterator[None]:
"""A context manager that can be used to run code at startup and shutdown."""
yield