Coverage for kwai/core/settings.py: 95%
62 statements
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
1"""Module for the settings of this application."""
2import os
4import tomli
5from pydantic import BaseModel, Field
7ENV_SETTINGS_FILE = "KWAI_SETTINGS_FILE"
10class SettingsException(Exception):
11 """Raised when a problem occurred while loading the settings."""
14class WebsiteSettings(BaseModel):
15 """Settings about the website."""
17 url: str
18 email: str
19 name: str
22class DatabaseSettings(BaseModel):
23 """Settings for the database connection."""
25 host: str
26 name: str
27 user: str
28 password: str
31class CORSSettings(BaseModel):
32 """Settings for configuring CORS."""
34 origins: list[str] = []
35 methods: list[str] = ["*"]
36 headers: list[str] = ["*"]
39class LoggerSettings(BaseModel):
40 """Settings for the logger."""
42 file: str = "kwai.log"
43 level: str = "DEBUG"
44 retention: str = "7 days"
45 rotation: str = "1 day"
48class EmailSettings(BaseModel):
49 """Settings for sending emails."""
51 host: str
52 port: int
53 ssl: bool = True
54 tls: bool = True
55 user: str | None = None
56 password: str | None = None
57 address: str = Field(alias="from")
60class RedisSettings(BaseModel):
61 """Settings for redis."""
63 host: str
64 port: int = 6379
65 password: str | None = None
66 logger: LoggerSettings | None = None
69class SecuritySettings(BaseModel):
70 """Setting or security."""
72 access_token_expires_in: int = 60 # minutes
73 refresh_token_expires_in: int = 43200 # 30 days
74 jwt_algorithm: str = "HS256"
75 jwt_secret: str
76 jwt_refresh_secret: str
79class TemplateSettings(BaseModel):
80 """Settings for template."""
82 path: str
85class Settings(BaseModel):
86 """Class with settings."""
88 security: SecuritySettings
90 template: TemplateSettings
92 logger: LoggerSettings | None = None
94 cors: CORSSettings | None = None
96 db: DatabaseSettings
98 website: WebsiteSettings
100 email: EmailSettings
102 redis: RedisSettings
105def get_settings() -> Settings:
106 """Dependency function for creating the Settings instance.
108 The settings are cached with lru_cache, which means the file is only loaded ounce.
110 :raises:
111 core.settings.SettingsException: Raised when the env variable is not set, or
112 when the file
113 can't be read.
114 """
115 if ENV_SETTINGS_FILE in os.environ:
116 settings_file = os.environ.get(ENV_SETTINGS_FILE, "")
117 try:
118 with open(settings_file, mode="rb") as file_handle:
119 return Settings.parse_obj(tomli.load(file_handle))
120 except OSError as exc:
121 raise SettingsException(f"Could not load {settings_file}") from exc
122 raise SettingsException(
123 f"{ENV_SETTINGS_FILE} should be set as environment variable"
124 )