import secrets from pathlib import Path from fuware.core.settings.db_providers import AbstractDBProvider, SQLiteProvider from pydantic_settings import BaseSettings # type: ignore def determine_secrets(data_dir: Path, production: bool) -> str: if not production: return "shh-secret-test-key" secrets_file = data_dir.joinpath(".secret") if secrets_file.is_file(): with open(secrets_file) as f: return f.read() else: data_dir.mkdir(parents=True, exist_ok=True) with open(secrets_file, "w") as f: new_secret = secrets.token_hex(32) f.write(new_secret) return new_secret class AppSettings(BaseSettings): PRODUCTION: bool BASE_URL: str = "http://localhost:8080" """trailing slashes are trimmed (ex. `http://localhost:8080/` becomes ``http://localhost:8080`)""" HOST_IP: str = "*" API_HOST: str = "0.0.0.0" API_PORT: int = 9000 API_DOCS: bool = True ALLOW_SIGNUP: bool = False @property def DOCS_URL(self) -> str | None: return "/docs" if self.API_DOCS else None @property def REDOC_URL(self) -> str | None: return "/redoc" if self.API_DOCS else None # =============================================== # Database Configuration DB_ENGINE: str = "sqlite" # Options: 'sqlite', 'postgres' DB_PROVIDER: AbstractDBProvider | None = None @property def DB_URL(self) -> str | None: return self.DB_PROVIDER.db_url if self.DB_PROVIDER else None @property def DB_URL_PUBLIC(self) -> str | None: return self.DB_PROVIDER.db_url_public if self.DB_PROVIDER else None def app_settings_constructor(data_dir: Path, production: bool, env_file: Path, env_encoding="utf-8") -> AppSettings: """ app_settings_constructor is a factory function that returns an AppSettings object. It is used to inject the required dependencies into the AppSettings object and nested child objects. AppSettings should not be substantiated directly, but rather through this factory function. """ app_settings = AppSettings( _env_file=env_file, # type: ignore _env_file_encoding=env_encoding, # type: ignore **{"SECRET": determine_secrets(data_dir, production)}, ) app_settings.DB_PROVIDER = SQLiteProvider(data_dir=data_dir) return app_settings