Skip to content

Settings

Unfazed uses a Python module as its settings file. The module is loaded via the UNFAZED_SETTINGS_MODULE environment variable and validated through Pydantic models. This gives you type-safe configuration with sensible defaults.

Quick Start

1. Create a settings module

# entry/settings/__init__.py

UNFAZED_SETTINGS = {
    "DEBUG": True,
    "PROJECT_NAME": "myproject",
    "ROOT_URLCONF": "entry.routes",
    "INSTALLED_APPS": [
        "apps.account",
        "apps.blog",
    ],
    "MIDDLEWARE": [
        "unfazed.middleware.internal.common.CommonMiddleware",
    ],
}

2. Point the environment variable to your module

# asgi.py
import os
from unfazed.core import Unfazed

os.environ.setdefault("UNFAZED_SETTINGS_MODULE", "entry.settings")

application = Unfazed()

When Unfazed() is instantiated it reads UNFAZED_SETTINGS_MODULE, imports the module, and validates the UNFAZED_SETTINGS dict against the UnfazedSettings Pydantic model.

Built-in Settings

All built-in settings live inside the UNFAZED_SETTINGS dict. The table below lists every recognised key.

Key Type Default Description
DEBUG bool True Enable debug mode. In debug mode, CommonMiddleware renders a detailed error page on unhandled exceptions.
PROJECT_NAME str "Unfazed" Human-readable project name. Used as the CLI group name.
VERSION str "0.0.1" Project version string.
ROOT_URLCONF str \| None None Dotted path to the root URL configuration module (must export a patterns list).
INSTALLED_APPS List[str] [] Dotted paths to application packages. Each must contain an app.py with an AppConfig class.
MIDDLEWARE List[str] [] Dotted paths to middleware classes, executed in order.
DATABASE Database \| None None Database configuration for Tortoise ORM. See the Tortoise ORM doc.
CACHE Dict[str, Cache] \| None None Named cache backend configuration. See the Cache doc.
LOGGING Dict[str, Any] \| None None Python dictConfig-style logging configuration. Merged with Unfazed defaults. See the Logging doc.
LIFESPAN List[str] \| None None Dotted paths to lifespan classes. See the Lifespan doc.
OPENAPI OpenAPI \| None None OpenAPI documentation configuration. See the OpenAPI doc.
CORS Cors \| None None CORS middleware configuration. See the Middleware doc.
TRUSTED_HOST TrustedHost \| None None Trusted-host middleware configuration. See the Middleware doc.
GZIP GZip \| None None GZip middleware configuration. See the Middleware doc.

The Settings Proxy

Unfazed exposes a global settings object that acts as a lazy, cached proxy to your settings module.

from unfazed.conf import settings

unfazed_settings = settings["UNFAZED_SETTINGS"]
print(unfazed_settings.PROJECT_NAME)

settings is an instance of SettingsProxy. On first access of a key it:

  1. Imports the module pointed to by UNFAZED_SETTINGS_MODULE.
  2. Looks up the key in the module's namespace.
  3. Validates the value against the registered Pydantic model.
  4. Caches the validated instance for subsequent access.

You can also use it like a dict — set, delete, and iterate:

settings["MY_KEY"] = my_model_instance
del settings["MY_KEY"]
settings.clear()

Custom Settings

Apps can define their own settings sections using the @register_settings decorator:

# myapp/settings.py
from pydantic import BaseModel
from unfazed.conf import register_settings


@register_settings("MYAPP_SETTINGS")
class MyAppSettings(BaseModel):
    api_key: str
    timeout: int = 30
    retry: bool = True

Then add the corresponding dict to your project settings module:

# entry/settings/__init__.py

UNFAZED_SETTINGS = { ... }

MYAPP_SETTINGS = {
    "api_key": "sk-xxx",
    "timeout": 60,
}

Access it anywhere:

from unfazed.conf import settings

myapp = settings["MYAPP_SETTINGS"]
print(myapp.api_key)   # "sk-xxx"
print(myapp.timeout)   # 60
print(myapp.retry)     # True (default)

The @register_settings decorator registers the Pydantic model with SettingsProxy so that the raw dict is validated and converted to a typed object on first access. If a key is registered twice, a UserWarning is emitted and the previous registration is overwritten.

Example: Full Settings File

Below is a typical settings module generated by unfazed startproject:

import os

DEPLOY = os.getenv("DEPLOY", "dev")
PROJECT_NAME = os.getenv("PROJECT_NAME", "myproject")
SECRET = os.getenv("SECRET", "change-me")

UNFAZED_SETTINGS = {
    "DEBUG": DEPLOY != "prod",
    "PROJECT_NAME": PROJECT_NAME,
    "ROOT_URLCONF": "entry.routes",
    "INSTALLED_APPS": [],
    "MIDDLEWARE": [
        "unfazed.middleware.internal.common.CommonMiddleware",
    ],
    "LOGGING": {
        "formatters": {
            "standard": {
                "format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
            },
        },
        "handlers": {
            "default": {
                "level": "INFO",
                "formatter": "standard",
                "class": "logging.handlers.RotatingFileHandler",
                "filename": "logs/unfazed.log",
            },
        },
        "loggers": {
            "common": {
                "handlers": ["default"],
                "level": "INFO",
            },
        },
    },
    "OPENAPI": {
        "servers": [
            {"url": "http://127.0.0.1:9527", "description": "Local dev"},
        ],
        "info": {
            "title": PROJECT_NAME,
            "version": "1.0.0",
            "description": f"API for {PROJECT_NAME}",
        },
        "allow_public": DEPLOY != "prod",
    },
}

API Reference

UnfazedSettings

class UnfazedSettings(BaseModel)

Pydantic model that validates the UNFAZED_SETTINGS dict. See the Built-in Settings table for all fields and defaults.

SettingsProxy

class SettingsProxy(Storage[T])

Lazy, caching proxy for the settings module.

Method / Property Description
__getitem__(key) Return the validated settings object for key. Raises KeyError if the key is not found.
__setitem__(key, value) Store a pre-built settings instance.
__delitem__(key) Remove a cached settings instance.
clear() Reset all cached instances and the imported settings module reference.
register_client_cls(key, cls) Register a Pydantic model class for a given settings key. Emits UserWarning on duplicate registration.
settingskv (property) Lazily imports and returns the raw settings module namespace as a dict.

register_settings

@register_settings(key: str)
class MySettings(BaseModel): ...

Class decorator that registers a Pydantic model with the global settings proxy under the given key.