Last active
January 18, 2023 23:27
-
-
Save ankona/8e5391e0a07edc3f6c629219477d17b5 to your computer and use it in GitHub Desktop.
pseudocode for generic config loading from single datasource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Generic, TypeVar, Union, Optional, Dict, Type, Any | |
from enum import Enum | |
from pydantic import BaseModel | |
from fastapi import APIRouter, FastAPI | |
T = TypeVar('T') | |
class ConfigType(str, Enum): | |
app = "ac" | |
model = "mc" | |
class AppConfig(BaseModel): | |
a: Optional[str] = None | |
b: Optional[int] = None | |
class ModelConfig(BaseModel): | |
x: Optional[str] = None | |
y: Optional[int] = None | |
config_mapper = { | |
ConfigType.app: { "v": lambda x: True, "m": AppConfig}, | |
ConfigType.model: { "v": lambda x: True, "m": ModelConfig} | |
} | |
class ConfigManager(Generic[T]): | |
def _query(self, key: str) -> Optional[T]: | |
d = {'fake': {}} | |
return d.get(key, None) | |
def _query_raw(self, key: str) -> Dict[str, Any]: | |
d = {'fake': {}} | |
return d | |
def __init__(self): | |
# todo: figure out how to compare | |
# T to [x['m'] == T for x in config_mapper] | |
self.config_type = ConfigType.app | |
def load(self, item_id: str) -> T: | |
data = self._query(item_id) | |
if data: | |
return data | |
cfg = config_mapper[self.config_type] | |
m = cfg['m'] | |
return m() | |
def load_raw(self, item_id: str) -> Dict[str, Any]: | |
data = self._query_raw(item_id) | |
return data | |
app = FastAPI() | |
# model-free retrieval | |
@app.get("/config/{config_type}/{item_id}") | |
def get_config_dict(config_type: ConfigType, item_id: str) -> Dict[str, str]: | |
mapping = config_mapper[config_type] | |
t: Type = mapping['m'] | |
loader = ConfigManager[t]() | |
data = loader.load_raw(item_id) | |
return data | |
# custom endpoints that have concrete model types | |
@app.get("/app_config/{item_id}") | |
def get_app_config(item_id: str) -> AppConfig: | |
loader = ConfigManager[AppConfig]() | |
data = loader.load(item_id) | |
return data | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment