Skip to main content

Manage your application settings with Pydantic models, storing them in JSON file.

Project description

Pydantic File Settings

PyPI version License: MIT Python Versions

Manage your application settings with Pydantic models, storing them in a JSON file.

Features

  • 🚀 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
  • 💪 Flexible: Create, load, and save settings with ease

Installation

pip install pydantic-file-settings

Quick Start

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 file with default values
settings = MyAppSettings.create("./config")

# Load existing settings
settings = MyAppSettings.load("./config")

# Modify and save settings
settings.debug_mode = True
settings.save()

Usage

Defining Your Settings

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)

Creating Settings

To create a new settings file:

# Create settings (raises SettingsExistsError if file exists)
settings = MyAppSettings.create("./config")

# Create settings, overwriting if file already exists
settings = MyAppSettings.create("./config", exists_ok=True)

Loading Settings

To load existing settings:

# Load settings (raises SettingsNotFoundError if file doesn't exist)
settings = MyAppSettings.load("./config")

# Load settings, creating file with defaults if it doesn't exist
settings = MyAppSettings.load("./config", create_if_missing=True)

Saving Settings

After modifying settings, save them back to the file:

settings.app_name = "New App Name"
settings.save()

Checking if Settings Exist

You can check if a settings file exists:

if MyAppSettings.exists("./config"):
    print("Settings file found!")

Advanced Usage

Custom Filename

By default, settings are stored in settings.json. You can customize the filename:

class MyAppSettings(FileSettings):
    __FILENAME__ = "app_config.json"
    
    app_name: str = "My App"

Environment Variables

Pydantic File Settings supports loading values from environment variables. Use the validation_alias parameter in Field:

class MyAppSettings(FileSettings):
    api_key: str = Field(default="", validation_alias="MY_APP_API_KEY")

Validation

Leverage Pydantic's validation features:

from pydantic import Field, field_validator

class MyAppSettings(FileSettings):
    port: int = Field(default=8000, ge=1024, le=65535)
    
    @field_validator("port")
    @classmethod
    def port_must_be_even(cls, v: int) -> int:
        if v % 2 != 0:
            raise ValueError("Port must be an even number")
        return v

BaseSettings

The library also exports BaseSettings with validate_assignment=True enabled, useful when you need validation without file storage:

from pydantic_file_settings import BaseSettings

class RuntimeConfig(BaseSettings):
    debug: bool = False

Exception Reference

Exception Raised by When
SettingsError Base exception for all settings errors
SettingsNotFoundError load() Settings file doesn't exist
SettingsExistsError create() Settings file already exists (when exists_ok=False)
ValueError load() Settings file contains invalid JSON or data
OSError save() Failed to write settings file (e.g., permission denied)

Error Handling Example

from pydantic_file_settings import (
    FileSettings,
    SettingsError,
    SettingsNotFoundError,
    SettingsExistsError,
)

# Handling load errors
try:
    settings = MyAppSettings.load("./config")
except SettingsNotFoundError:
    print("Settings file not found!")
except ValueError:
    print("Invalid settings data!")

# Handling create errors
try:
    settings = MyAppSettings.create("./config")
except SettingsExistsError:
    print("Settings file already exists!")

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgements

  • Pydantic for the awesome data validation library

Made with ❤️ by Ruslan Iskov

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_file_settings-0.1.0.tar.gz (37.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_file_settings-0.1.0-py3-none-any.whl (5.6 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_file_settings-0.1.0.tar.gz.

File metadata

  • Download URL: pydantic_file_settings-0.1.0.tar.gz
  • Upload date:
  • Size: 37.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pydantic_file_settings-0.1.0.tar.gz
Algorithm Hash digest
SHA256 c9ca0f7594181ff1c561fc0f5b606b2748f86a70aae28cc6d3d3d7fdaefe61fb
MD5 b0aee64d52767baef087020df8b95403
BLAKE2b-256 5fe445773ea853be0ba78894dbe2330eb5d9faa9470962897535f62ddf538ad2

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_file_settings-0.1.0.tar.gz:

Publisher: publish.yml on ruslan-rv-ua/pydantic-file-settings

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pydantic_file_settings-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_file_settings-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0e0eef39c044b17cc175e761ae6b82d7a7240f5100dc4dc0e71739c36defa539
MD5 982b3c5cb7299e0733f2cfa5cfe09570
BLAKE2b-256 7c2c48357357e1099816e063011fad34b7cc07cd83fcd2ed1c48d1967e9963f5

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_file_settings-0.1.0-py3-none-any.whl:

Publisher: publish.yml on ruslan-rv-ua/pydantic-file-settings

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page