Use pydantic settings instead of python-dotenv

This commit is contained in:
2024-02-10 12:59:55 +03:00
parent 3f957db2eb
commit c2d7fd41d7
2 changed files with 10 additions and 44 deletions

View File

@@ -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
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')

View File

@@ -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
aiohttp==3.8.6
pydantic==2.3.0
pydantic-settings==2.1.0