Manage your application settings with Pydantic models, storing them in a JSON file.
- 🚀 Easy to use: Extend from
FileSettings
and you're good to go! - 🔒 Type-safe: Leverage Pydantic's powerful type checking and validation
- 💾 File-based: Store your settings in a JSON file for easy management
- 🔄 Auto-reload: Automatically load settings from file
- 💪 Flexible: Create, load, and save settings with ease
pip install pydantic-file-settings
Here's a simple example to get you started:
from pydantic_file_settings import FileSettings
from pydantic import Field
class MyAppSettings(FileSettings):
app_name: str = "My Awesome App"
debug_mode: bool = False
max_connections: int = Field(default=100, ge=1, le=1000)
# Create settings
settings = MyAppSettings.create("./config")
# Load existing settings
settings = MyAppSettings.load("./config")
# Modify and save settings
settings.debug_mode = True
settings.save()
Inherit from FileSettings
and define your settings as class attributes:
from pydantic_file_settings import FileSettings
from pydantic import Field
class MyAppSettings(FileSettings):
app_name: str
debug_mode: bool = False
max_connections: int = Field(default=100, ge=1, le=1000)
api_key: str = Field(default="", env="MY_APP_API_KEY")
To create a new settings file:
settings = MyAppSettings.create("./config")
To load existing settings:
settings = MyAppSettings.load("./config")
After modifying settings, save them back to the file:
settings.app_name = "New App Name"
settings.save()
You can check if a settings file exists:
if MyAppSettings.exists("./config"):
print("Settings file found!")
Pydantic File Settings supports loading values from environment variables. Use the env
parameter in Field
:
class MyAppSettings(FileSettings):
api_key: str = Field(default="", env="MY_APP_API_KEY")
Leverage Pydantic's validation features:
from pydantic import Field, validator
class MyAppSettings(FileSettings):
port: int = Field(default=8000, ge=1024, le=65535)
@validator("port")
def port_must_be_even(cls, v):
if v % 2 != 0:
raise ValueError("Port must be an even number")
return v
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
- Pydantic for the awesome data validation library
- Ruslan Iskov for creating and maintaining this project
Made with ❤️ by Ruslan Iskov