From c2d7fd41d75785fac188be8335d3f3fb5a3b3112 Mon Sep 17 00:00:00 2001 From: Sergey Elpashev Date: Sat, 10 Feb 2024 12:59:55 +0300 Subject: [PATCH] Use pydantic settings instead of python-dotenv --- neuroapi/config.py | 49 +++++++--------------------------------------- requirements.txt | 5 +++-- 2 files changed, 10 insertions(+), 44 deletions(-) diff --git a/neuroapi/config.py b/neuroapi/config.py index 3d82414..3ddba4f 100644 --- a/neuroapi/config.py +++ b/neuroapi/config.py @@ -1,45 +1,10 @@ -import os -import tomllib -from typing import List, Optional +from typing import Optional -from attr import dataclass -from dotenv import load_dotenv - -from neuroapi.types import Singleton - -from .types._helpers import * +from pydantic import Field +from pydantic_settings import BaseSettings -@dataclass -class Settings: - time: List[str] - - @staticmethod - def from_dict(obj: Any) -> 'Settings': - assert isinstance(obj, dict) - time = from_list(from_str, obj.get("time", [])) - return Settings(time) - - def to_dict(self) -> dict: - result: dict = {} - result['time'] = from_list(from_str, self.time) - return result - -class Config(Singleton): - api_url: str - settings: Settings - token: Optional[str] - proxy_token: Optional[str] - def __init__(self): - load_dotenv(os.path.join(os.path.dirname(__file__), '..', '.env')) - if not os.path.exists(os.path.join(os.path.dirname(__file__), '..', 'settings.toml')): raise Exception('Settings.toml must be in root folder') - with open(os.path.join(os.path.dirname(__file__), '..', 'settings.toml'), 'rb') as f: - settings = tomllib.load(f) - self.settings = Settings.from_dict(settings) - self.api_url = os.environ.get('API_URL') - self.token = os.environ.get('TOKEN') - if self.token == '': - self.token = None - self.proxy_token = os.environ.get('PROXY_TOKEN') - if self.proxy_token == '': - self.proxy_token = None \ No newline at end of file +class GlobalConfig(BaseSettings): + api_url: str = Field("http://localhost:3000", alias='API_URL') + token: Optional[str] = Field(None, alias='TOKEN') + proxy_token: Optional[str] = Field(None, alias='PROXY_TOKEN') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 2333377..87ec6ba 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ aiogram==3.1.1 aioschedule @ https://github.com/AleksHeller/python-aioschedule/archive/refs/heads/master.zip -python-dotenv==1.0.0 requests==2.31.0 python-dateutil==2.8.2 -aiohttp==3.8.6 \ No newline at end of file +aiohttp==3.8.6 +pydantic==2.3.0 +pydantic-settings==2.1.0 \ No newline at end of file