fix: Remove global state (#1216)

* Remove all global settings state

* chore: remove autogenerated class

* chore: cleanup

* chore: merge conflicts
This commit is contained in:
Pablo Orgaz 2023-11-12 22:20:36 +01:00 committed by GitHub
parent f394ca61bb
commit 022bd718e3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 286 additions and 190 deletions

View file

@ -2,7 +2,7 @@ from typing import Literal
from pydantic import BaseModel, Field
from private_gpt.settings.settings_loader import load_active_profiles
from private_gpt.settings.settings_loader import load_active_settings
class CorsSettings(BaseModel):
@ -114,4 +114,29 @@ class Settings(BaseModel):
openai: OpenAISettings
settings = Settings(**load_active_profiles())
"""
This is visible just for DI or testing purposes.
Use dependency injection or `settings()` method instead.
"""
unsafe_settings = load_active_settings()
"""
This is visible just for DI or testing purposes.
Use dependency injection or `settings()` method instead.
"""
unsafe_typed_settings = Settings(**unsafe_settings)
def settings() -> Settings:
"""Get the current loaded settings from the DI container.
This method exists to keep compatibility with the existing code,
that require global access to the settings.
For regular components use dependency injection instead.
"""
from private_gpt.di import global_injector
return global_injector.get(Settings)

View file

@ -2,6 +2,7 @@ import functools
import logging
import os
import sys
from collections.abc import Iterable
from pathlib import Path
from typing import Any
@ -28,7 +29,11 @@ active_profiles: list[str] = unique_list(
)
def load_profile(profile: str) -> dict[str, Any]:
def merge_settings(settings: Iterable[dict[str, Any]]) -> dict[str, Any]:
return functools.reduce(deep_update, settings, {})
def load_settings_from_profile(profile: str) -> dict[str, Any]:
if profile == "default":
profile_file_name = "settings.yaml"
else:
@ -42,9 +47,11 @@ def load_profile(profile: str) -> dict[str, Any]:
return config
def load_active_profiles() -> dict[str, Any]:
def load_active_settings() -> dict[str, Any]:
"""Load active profiles and merge them."""
logger.info("Starting application with profiles=%s", active_profiles)
loaded_profiles = [load_profile(profile) for profile in active_profiles]
merged: dict[str, Any] = functools.reduce(deep_update, loaded_profiles, {})
loaded_profiles = [
load_settings_from_profile(profile) for profile in active_profiles
]
merged: dict[str, Any] = merge_settings(loaded_profiles)
return merged