Skip to content

Settings

plateforme.core.settings

This module provides utilities for managing settings within the Plateforme framework.

LoggingFormatterSettingsDict module-attribute

LoggingFormatterSettingsDict = Union[
    "LoggingCustomFormatterSettingsDict",
    "LoggingDefaultFormatterSettingsDict",
    "LoggingJsonFormatterSettingsDict",
    "LoggingSimpleFormatterSettingsDict",
]

Plateforme logging formatter settings dictionary.

LoggingFormatterSettings module-attribute

LoggingFormatterSettings = Union[
    "LoggingCustomFormatterSettings",
    "LoggingDefaultFormatterSettings",
    "LoggingJsonFormatterSettings",
    "LoggingSimpleFormatterSettings",
]

Plateforme logging formatter settings.

LoggingHandlerSettingsDict module-attribute

LoggingHandlerSettingsDict = Union[
    "LoggingCustomHandlerSettingsDict",
    "LoggingFileHandlerSettingsDict",
    "LoggingStreamHandlerSettingsDict",
]

Plateforme logging handler settings dictionary.

LoggingHandlerSettings module-attribute

LoggingHandlerSettings = Union[
    "LoggingCustomHandlerSettings",
    "LoggingFileHandlerSettings",
    "LoggingStreamHandlerSettings",
]

Plateforme logging handler settings.

ADJECTIVES module-attribute

ADJECTIVES = (
    "Apex",
    "Arc",
    "Astro",
    "Atomic",
    "Black",
    "Blue",
    "Call",
    "Cold",
    "Core",
    "Cyber",
    "Dark",
    "Data",
    "Deep",
    "Delta",
    "Dual",
    "Edge",
    "Epsilon",
    "Fast",
    "Flat",
    "Flow",
    "Flux",
    "Gamma",
    "Gen",
    "Gray",
    "Grid",
    "Hard",
    "Hash",
    "Heavy",
    "High",
    "Hot",
    "Hyper",
    "Iron",
    "Kappa",
    "Lab",
    "Lambda",
    "Late",
    "Lead",
    "Lens",
    "Line",
    "Mod",
    "Mass",
    "Max",
    "Mega",
    "Nano",
    "Neo",
    "Net",
    "Neural",
    "Nova",
    "Omega",
    "Port",
    "Prime",
    "Proto",
    "Pull",
    "Quad",
    "Raw",
    "Red",
    "Sharp",
    "Sigma",
    "Solid",
    "Sub",
    "Tech",
    "Var",
    "Wire",
    "Zeta",
)

A list of adjectives used to generate random application titles.

NOUNS module-attribute

NOUNS = (
    "Array",
    "Axis",
    "Base",
    "Bit",
    "Block",
    "Bool",
    "Boot",
    "Buffer",
    "Bus",
    "Byte",
    "Cache",
    "Cell",
    "Chain",
    "Cube",
    "Dict",
    "Diff",
    "Disk",
    "Dock",
    "Eval",
    "Exec",
    "File",
    "Flag",
    "Frame",
    "Func",
    "Gate",
    "Graph",
    "Group",
    "Heap",
    "Hook",
    "Host",
    "Hub",
    "Init",
    "Int",
    "Item",
    "Join",
    "Key",
    "Link",
    "List",
    "Loop",
    "Map",
    "Mesh",
    "Mode",
    "Num",
    "Node",
    "Null",
    "Page",
    "Path",
    "Pipe",
    "Pod",
    "Pool",
    "Proc",
    "Queue",
    "Ram",
    "Ring",
    "Root",
    "Scan",
    "Set",
    "Shell",
    "Stack",
    "Sync",
    "Task",
    "Term",
    "Tree",
    "Word",
)

A list of nouns used to generate random application titles.

ContactInfoDict

Bases: TypedDict

Contact information dictionary.

name instance-attribute

name: Required[str]

The name of the contact person or organization.

email instance-attribute

email: Email

The email address of the contact person or organization. It must be formatted as a valid email address. Defaults to None.

url instance-attribute

A URL pointing to the contact information. It must be formatted as a valid URL. Defaults to None.

ContactInfo

ContactInfo(**data: Any)

Bases: BaseModel

Contact information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LicenseInfoDict

Bases: TypedDict

License information dictionary.

name instance-attribute

name: Required[str]

The license name.

identifier instance-attribute

identifier: str

An SPDX license expression. The identifier field is mutually exclusive with the url field. It is available within OpenAPI since version 3.1.0. Defaults to None.

url instance-attribute

A URL pointing to the license information. The url field is mutually exclusive with the identifier field. Defaults to None.

LicenseInfo

LicenseInfo(**data: Any)

Bases: BaseModel

License information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

APIRouterSettingsDict

Bases: TypedDict

Plateforme API router settings dictionary.

dependencies instance-attribute

dependencies: Sequence[DependsInfo] | None

A collection of dependencies to be applied to all the path operations in the router (using Depends). Defaults to None.

default_response_class instance-attribute

default_response_class: type[Response]

The default response class to be used for path operations. Defaults to JSONResponse.

responses instance-attribute

responses: dict[int | str, dict[str, Any]] | None

Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

callbacks instance-attribute

callbacks: list[BaseRoute] | None

OpenAPI callbacks that should apply to all path operations in the router. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

routes instance-attribute

routes: list[BaseRoute] | None

A collection of routes to be included in the router to serve incoming HTTP and WebSocket requests. This is not recommended for general use, as it bypasses the traditional routing system. Defaults to None.

redirect_slashes instance-attribute

redirect_slashes: bool

Whether to redirect requests with a trailing slash to the same path without the trailing slash. Defaults to True.

default instance-attribute

default: ASGIApp | None

The default function handler to be used for the router. It is used to handle '404 Not Found' errors. Defaults to None.

dependency_overrides_provider instance-attribute

dependency_overrides_provider: Any

An optional dependency overrides provider used internally by the router. Defaults to None.

route_class instance-attribute

route_class: type[APIRoute]

The request route class to be used for the router.

lifespan instance-attribute

lifespan: Lifespan[APIManager] | None

The Lifespan context manager handler for events to be executed when the router starts up and shuts down. It defines a collection of on_startup and on_shutdown events. Defaults to None.

include_in_schema instance-attribute

include_in_schema: bool

Include (or not) all the path operations in the router in the generated OpenAPI schema. This affects the generated OpenAPI, visible at '/docs'. Defaults to True.

APIRouterSettings

APIRouterSettings(**data: Any)

Bases: BaseModel

Plateforme API router settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

APISettingsDict

Bases: TypedDict

Plateforme API settings dictionary.

openapi_url instance-attribute

openapi_url: str | None

The URL where the OpenAPI schema will be served from. If you set it to None, no OpenAPI schema will be served publicly, and the default automatic endpoints '/docs' and '/redoc' will also be disabled. Defaults to '/openapi.json'.

openapi_tags instance-attribute

openapi_tags: list[dict[str, Any]] | None

A list of tags used by OpenAPI, these are the same tags you can set in the path operations. The order of the tags can be used to specify the order shown in tools like Swagger UI, used in the automatic path '/docs'. It's not required to specify all the tags used. The tags that are not declared MAY be organized randomly or based on the tool's logic. Each tag name in the list MUST be unique. The value of each item is a dict containing: - name: The name of the tag. - description: A short description of the tag. CommonMark syntax MAY be used for rich text representation. - externalDocs: Additional external documentation for this tag. If provided, it would contain a dict with: - description: A short description of the target documentation. CommonMark syntax MAY be used for rich text representation. - url: The URL for the target documentation. Value MUST be in the form of a URL. Defaults to None.

servers instance-attribute

servers: list[dict[str, Any]] | None

A list of dicts with connectivity information to a target server. You would use it, for example, if your application is served from different domains and you want to use the same Swagger UI in the browser to interact with each of them (instead of having multiple browser tabs open). Or if you want to leave fixed the possible URLs. If the servers list is not provided, or is an empty list, the default value would be a dict with a url value of '/'. Each item in the list is a dict containing: - url: A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named inside brackets {}. - description: An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation. - variables: A dict between a variable name and its value. The value is used for substitution in the server's URL template. Defaults to None.

dependencies instance-attribute

dependencies: Sequence[DependsInfo] | None

A collection of dependencies to be applied to all the path operations in the router (using Depends). Defaults to None.

default_response_class instance-attribute

default_response_class: type[Response]

The default response class to be used for path operations. Defaults to JSONResponse.

redirect_slashes instance-attribute

redirect_slashes: bool

Whether to redirect requests with a trailing slash to the same path without the trailing slash. Defaults to True.

docs_url instance-attribute

docs_url: str | None

The path to the automatic interactive API documentation. It is handled in the browser by Swagger UI. The default URL is '/docs'. You can disable it by setting it to None. If openapi_url is set to None, this will be automatically disabled. Defaults to '/docs'.

redoc_url instance-attribute

redoc_url: str | None

The path to the alternative automatic interactive API documentation provided by ReDoc. The default URL is '/redoc'. You can disable it by setting it to None. If openapi_url is set to None, this will be automatically disabled. Defaults to '/redoc'.

swagger_ui_oauth2_redirect_url instance-attribute

swagger_ui_oauth2_redirect_url: str | None

The OAuth2 redirect endpoint for the Swagger UI. By default it is /docs/oauth2-redirect. This is only used if you use OAuth2 (with the "Authorize" button) with Swagger UI. Defaults to '/docs/oauth2-redirect'.

swagger_ui_init_oauth instance-attribute

swagger_ui_init_oauth: dict[str, Any] | None

OAuth2 configuration for the Swagger UI, by default shown at '/docs'. Defaults to None.

middleware instance-attribute

middleware: Sequence[Middleware] | None

A list of middleware to be added when creating the application. You can do this with api.add_middleware() instead. Defaults to None.

exception_handlers instance-attribute

exception_handlers: (
    dict[
        int | type[Exception],
        Callable[
            [Request, Any], Coroutine[Any, Any, Response]
        ],
    ]
    | None
)

A dictionary with handlers for exceptions. You can use the decorator @api.exception_handler() instead. Defaults to None.

lifespan instance-attribute

lifespan: Lifespan[APIManager] | None

The Lifespan context manager handler for events to be executed when the router starts up and shuts down. It defines a collection of on_startup and on_shutdown events. Defaults to None.

openapi_prefix instance-attribute

openapi_prefix: str

A URL prefix for the OpenAPI URL. Defaults to ''.

root_path instance-attribute

root_path: str

A path prefix handled by a proxy that is not seen by the application but is seen by external clients, which affects things like Swagger UI. Defaults to ''.

root_path_in_servers instance-attribute

root_path_in_servers: bool

To disable automatically generating the URLs in the servers field in the autogenerated OpenAPI using the root_path. Defaults to True.

responses instance-attribute

responses: dict[int | str, dict[str, Any]] | None

Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

callbacks instance-attribute

callbacks: list[BaseRoute] | None

OpenAPI callbacks that should apply to all path operations. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

routes instance-attribute

routes: list[BaseRoute] | None

A collection of routes to be included in the router to serve incoming HTTP and WebSocket requests. This is not recommended for general use, as it bypasses the traditional routing system. Defaults to None.

webhooks instance-attribute

webhooks: APIRoute | None

Add OpenAPI webhooks. This is similar to callbacks but it doesn't require a response. Defaults to None.

include_in_schema instance-attribute

include_in_schema: bool

Whether the API should be included in the OpenAPI schema. Defaults to True.

swagger_ui_parameters instance-attribute

swagger_ui_parameters: dict[str, Any] | None

Additional parameters to pass to the Swagger UI. Defaults to None.

separate_input_output_schemas instance-attribute

separate_input_output_schemas: bool

Whether input and output schemas should be separate. Defaults to True.

extra instance-attribute

extra: dict[str, Any]

Additional parameters to pass to the application. Defaults to an empty dictionary.

APISettings

APISettings(**data: Any)

Bases: BaseModel

Plateforme API settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingCustomFormatterSettingsDict

Bases: TypedDict

Plateforme logging custom formatter settings dictionary.

type instance-attribute

type: Required[Literal['custom']]

The type of the formatter set as 'custom' and used to discriminate between different formatter types.

cls instance-attribute

cls: Required[str]

The fully qualified name of the custom formatter class to use. This should be a subclass of logging.Formatter.

extra instance-attribute

extra: dict[str, Any] | None

Extra parameters to pass to the custom formatter.

LoggingCustomFormatterSettings

LoggingCustomFormatterSettings(**data: Any)

Bases: BaseModel

Plateforme logging custom formatter settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingDefaultFormatterSettingsDict

Bases: TypedDict

Plateforme logging default formatter settings dictionary.

type instance-attribute

type: Required[Literal['default']]

The type of the formatter set as 'default' and used to discriminate between different formatter types.

asctime instance-attribute

asctime: bool

Human-readable time when the LogRecord was created. By default this is of the form '2003-07-08T16:49:45+0100'. Format: '%(asctime)s'. Defaults to False.

use_colors instance-attribute

use_colors: bool

Whether to use colors in the log output. This is only available in the default formatter. Defaults to False.

LoggingDefaultFormatterSettings

LoggingDefaultFormatterSettings(**data: Any)

Bases: BaseModel

Plateforme logging default formatter settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingJsonFormatterSettingsDict

Bases: TypedDict

Plateforme logging JSON formatter settings dictionary.

type instance-attribute

type: Required[Literal['json']]

The type of the formatter set as 'json' and used to discriminate between different formatter types.

levelname instance-attribute

levelname: bool

Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'). Defaults to True.

levelno instance-attribute

levelno: bool

Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL). Defaults to False.

message instance-attribute

message: bool

The logged message, computed as msg % args. This is set when Formatter.format() is invoked. Defaults to True.

timestamp instance-attribute

timestamp: bool

Human-readable timestamp when the LogRecord was created with timezone information. This is of the form '2024-01-19T03:04:40.131729+00:00' (the numbers after the dot are millisecond portion of the time, and the timezone is UTC). Defaults to True.

asctime instance-attribute

asctime: bool

Human-readable time when the LogRecord was created. By default this is of the form '2003-07-08T16:49:45+0100'. Defaults to False.

created instance-attribute

created: bool

Time when the LogRecord was created (as returned by time.time_ns() / 1e9). Defaults to False.

msecs instance-attribute

msecs: bool

Millisecond portion of the time when the LogRecord was created. Defaults to False.

name instance-attribute

name: bool

Name of the logger used to log the call. Defaults to True.

module instance-attribute

module: bool

Module (name portion of filename). Defaults to True.

funtion instance-attribute

funtion: bool

Name of function containing the logging call. Defaults to True.

lineno instance-attribute

lineno: bool

Source line number where the logging call was issued (if available). Defaults to True.

args instance-attribute

args: bool

The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary). Defaults to False.

msg instance-attribute

msg: bool

The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object. Defaults to False.

pathname instance-attribute

pathname: bool

Full pathname of the source file where the logging call was issued (if available). Defaults to False.

filename instance-attribute

filename: bool

Filename portion of pathname. Defaults to False.

process instance-attribute

process: bool

Process ID (if available). Defaults to False.

process_name instance-attribute

process_name: bool

Process name (if available). Defaults to False.

relative_created instance-attribute

relative_created: bool

Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded. Defaults to False.

exc_info instance-attribute

exc_info: bool

Exception tuple (like sys.exc_info) or, if no exception has occurred, None. Defaults to False.

stack_info instance-attribute

stack_info: bool

Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call. Defaults to False.

task_name instance-attribute

task_name: bool

A asyncio.Task name (if available). Defaults to False.

thread instance-attribute

thread: bool

Thread ID (if available). Defaults to False.

thread_name instance-attribute

thread_name: bool

Thread name (if available). Defaults to False.

extra instance-attribute

extra: bool

Wheiher to include all the user-defined extra fields in the log record. If True, the extra attributes of the log record will be serialized as a dictionary and included in the log record. Otherwise, the extra attributes will be ignored. Defaults to True.

LoggingJsonFormatterSettings

LoggingJsonFormatterSettings(**data: Any)

Bases: BaseModel

Plateforme logging JSON formatter settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingSimpleFormatterSettingsDict

Bases: TypedDict

Plateforme logging simple formatter settings dictionary.

type instance-attribute

type: Required[Literal['simple']]

The type of the formatter set as 'simple' and used to discriminate between different formatter types.

format instance-attribute

format: str

A format string in the given style for the logged output as a whole. The possible mapping keys are drawn from the LogRecord object's attributes. If not specified, '%(message)s' is used, which is just the logged message. Defaults to '[%(asctime)s] %(levelname)-8s: %(module)s:%(lineno)d - %(message)s'.

datefmt instance-attribute

datefmt: str

A format string in the given style for the date/time portion of the logged output. If not specified, the default described in formatTime() is used. Defaults to '%Y-%m-%dT%H:%M:%S%z'.

style instance-attribute

style: Literal['%', '{', '$']

Can be one of '%', '{', or '$' and determines how the format string will be merged with its data: using one of printf-style String Formatting (%), str.format() ({) or string.Template ($). This only applies to fmt and datefmt (e.g. '%(message)s' versus '{message}'), not to the actual log messages passed to the logging methods. However, there are other ways to use '{'- and '$'-formatting for log messages. Defaults to '%'.

raise_errors instance-attribute

raise_errors: bool

If True, incorrect or mismatched format and style will raise a ValueError. Defaults to True.

defaults instance-attribute

defaults: dict[str, Any] | None

A dictionary with default values to use in custom fields. Defaults to None.

LoggingSimpleFormatterSettings

LoggingSimpleFormatterSettings(**data: Any)

Bases: BaseModel

Plateforme logging simple formatter settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingCustomHandlerSettingsDict

Bases: TypedDict

Plateforme logging custom handler settings dictionary.

type instance-attribute

type: Required[Literal['custom']]

The type of the handler set as 'custom' and used to discriminate between different handler types.

cls instance-attribute

cls: Required[str]

The fully qualified name of the custom handler class to use. This should be a subclass of logging.Handler.

level instance-attribute

level: (
    Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
    | None
)

The logging level for the custom handler. Defaults to None.

filters instance-attribute

filters: list[str] | None

A list of logging filters to use for the custom handler. Each filter should be a fully qualified name of the filter class. Defaults to None.

formatter instance-attribute

formatter: str

The formatter name to use for the custom handler. Defaults to 'default'.

extra instance-attribute

extra: dict[str, Any] | None

Extra parameters to pass to the custom handler.

LoggingCustomHandlerSettings

LoggingCustomHandlerSettings(**data: Any)

Bases: BaseModel

Plateforme logging custom handler settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingFileHandlerSettingsDict

Bases: TypedDict

Plateforme logging file handler settings dictionary.

type instance-attribute

type: Required[Literal['file']]

The type of the handler set as 'file' and used to discriminate between different handler types.

level instance-attribute

level: (
    Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
    | None
)

The logging level for the file handler. Defaults to None.

filters instance-attribute

filters: list[str] | None

A list of logging filters to use for the file handler. Each filter should be a fully qualified name of the filter class. Defaults to None.

formatter instance-attribute

formatter: str

The formatter name to use for the file handler. Defaults to 'json'.

filename instance-attribute

filename: str | None

The filename to use for the handler. If not provided, the handler will use the default filename 'logs/plateforme.log', or 'logs/plateforme.jsonl' if the JSON formatter is used. Defaults to None.

max_bytes instance-attribute

max_bytes: int

The maximum number of bytes to store in the log file before rotating the file. Defaults to 10485760.

backup_count instance-attribute

backup_count: int

The number of backup files to keep when rotating the log file. Defaults to 5.

LoggingFileHandlerSettings

LoggingFileHandlerSettings(**data: Any)

Bases: BaseModel

Plateforme logging file handler settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingStreamHandlerSettingsDict

Bases: TypedDict

Plateforme logging stream handler settings dictionary.

type instance-attribute

type: Required[Literal['stream']]

The type of the handler set as 'stream' and used to discriminate between different handler types.

level instance-attribute

level: (
    Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
    | None
)

The logging level for the stream handler. Defaults to None.

filters instance-attribute

filters: list[str] | None

A list of logging filters to use for the stream handler. Each filter should be a fully qualified name of the filter class. Defaults to None.

formatter instance-attribute

formatter: str

The formatter name to use for the stream handler. Defaults to 'default'.

stream instance-attribute

stream: str

The stream to use for the handler. Defaults to 'ext://sys.stdout'.

LoggingStreamHandlerSettings

LoggingStreamHandlerSettings(**data: Any)

Bases: BaseModel

Plateforme logging stream handler settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

LoggingSettingsDict

Bases: TypedDict

Plateforme logging settings dictionary.

level instance-attribute

level: Literal[
    "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"
]

The logging level for the application. Defaults to 'INFO'.

filters instance-attribute

filters: dict[str, str]

A dictionary of logging filters used in the application with their names as keys and the fully qualified name of the filter class as values. By default, it includes one built-in filter under the key 'no_errors' that can be overridden. If provided, the custom filters are merged with these defaults. Defaults to an empty dictionary.

formatters instance-attribute

A dictionary of logging formatters used in the application. By default, it includes three built-in formatters under the keys 'default', 'color', and 'json' that can be overridden. If provided, the custom formatters are merged with these defaults. Defaults to an empty dictionary.

handlers instance-attribute

A dictionary of logging handlers used in the application. By default, it includes two built-in handlers under the keys 'stdout' and 'stderr' that can be overridden. If provided, the custom handlers are merged with these defaults. Defaults to an empty dictionary.

LoggingSettings

LoggingSettings(**data: Any)

Bases: BaseModel

Plateforme logging settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

NamespaceSettingsDict

Bases: TypedDict

Plateforme namespace settings dictionary.

alias instance-attribute

alias: str | None

The namespace alias used to define which database schema should store its resources in an application. Multiple namespaces can share the same alias within an application. It must be formatted to snake case and defaults to the namespace unique name (e.g. 'my_namespace' for 'my_namespace'). Defaults to None.

slug instance-attribute

slug: str | None

The namespace slug used to define which URL path should be used to access the namespace resources in an API. Multiple namespaces can share the same slug within an application. It must be formatted to kebab case and defaults to the kebab case of the namespace unique name (e.g. 'my-namespace' for 'my_namespace'). Defaults to None.

title instance-attribute

title: str | None

The namespace human-readable title that is used to display the namespace verbose name within an application. It defaults to the titleized version of the namespace unique name (e.g. 'My Namepsace' for 'my_namespace'). It is used within the API and will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

summary instance-attribute

summary: str | None

A short summary of the namespace. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

description instance-attribute

description: str | None

A description of the namespace. Supports Markdown (using CommonMark syntax). It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

version instance-attribute

version: str | None

The namespace version. It is used to define the version of the namespace, not the version of the OpenAPI specification or the version of the Plateforme framework being used. It will be added to the generated OpenAPI, visible at '/docs'. If not set, it will defaults to the application version. Defaults to None.

contact instance-attribute

contact: ContactInfo | ContactInfoDict | str | None

The contact information for the namespace exposed API. It can be provided either as a string with the contact name and optionally an email address, or as a dictionary. The following fields will be added to the generated OpenAPI, visible at '/docs': - name (str): The name of the contact person or organization. If not provided, it defaults to an empty string. - url (str): An URL pointing to the contact information. It must be formatted as a valid URL. - email (str): The email address of the contact person or organization. It must be formatted as a valid email address. Defaults to None.

license instance-attribute

license: LicenseInfo | LicenseInfoDict | str | None

The license information for the namespace exposed API. It can be provided either as a string with the license name, or as a dictionary. The following fields will be added to the generated OpenAPI, visible at '/docs': - name (str): The license name used for the API. - identifier (str): An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0. - url (str): An URL to the license used for the API. This must be formatted as a valid URL. Defaults to None.

terms_of_service instance-attribute

terms_of_service: str | None

A URL to the Terms of Service for the namespace exposed API. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

api instance-attribute

The namespace API settings. Defaults to an empty dictionary.

api_max_depth instance-attribute

api_max_depth: int

The maximum depth to walk through the resource path to collect manager methods from resource dependencies. It is used to generate the API routes for resources within the namespace. Defaults to 2.

api_max_selection instance-attribute

api_max_selection: int

The limit of resources to return for the API route selections. It is used when generating the API routes for resources within the namespace to avoid too many resources being returned. Defaults to 20.

deprecated instance-attribute

deprecated: bool | None

Whether the namespace is deprecated. Defaults to None.

NamespaceSettings

NamespaceSettings(**data: Any)

Bases: BaseModel

Plateforme namespace settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

PackageSettingsDict

Bases: TypedDict

Plateforme package settings dictionary.

namespace instance-attribute

namespace: str | None

The package namespace name that is used to load the package and its resources within an application. It is used to group resources and avoid name collisions. Defaults to None.

tags instance-attribute

tags: list[str | Enum] | None

A list of tags to be applied to all the path operations in the package router. It will be added to the generated OpenAPI, visible at '/docs'. If not provided, it defaults to the package slug. Defaults to None.

auto_mount instance-attribute

auto_mount: bool

Whether to automatically mount the package within the API. When disabled, the package must be manually mounted. Defaults to True.

api instance-attribute

The package API settings. Defaults to an empty dictionary.

api_max_depth instance-attribute

api_max_depth: int

The maximum depth to walk through the resource path to collect manager methods from resource dependencies. It is used to generate the API routes for resources within the package. Defaults to 2.

api_max_selection instance-attribute

api_max_selection: int

The limit of resources to return for the API route selections. It is used when generating the API routes for resources within the package to avoid too many resources being returned. Defaults to 20.

api_resources instance-attribute

api_resources: bool | Sequence[str]

A boolean, or a list of module or resource fully qualified names relative to the package that declares the top-level resources to include from the package within the API. When set to True, it includes all resources exposed within the __init__.py file of the package. When set to False, the API will not include any resources from the package. Permissions and access control can be applied to these resources. Defaults to True.

api_services instance-attribute

api_services: bool | Sequence[str]

A boolean, or a list of module or service fully qualified names relative to the package that declares the services to include from the package within the API. When set to True, it includes all services exposed within the __init__.py file of the package. When set to False, the API will not include any services from the package. Permissions and access control can be applied to these services. Defaults to True.

deprecated instance-attribute

deprecated: bool | None

Whether the package is deprecated. Defaults to None.

file_path instance-attribute

file_path: str | None

A string that defines the filesystem path of the package module. It is used to load package related assets from the filesystem. It defaults to the resolved package module path when not provided. Defaults to None.

PackageSettings

PackageSettings(**data: Any)

Bases: BaseModel

Plateforme package settings.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/models.py
def __init__(self, /, **data: Any) -> None:
    """Initialize a model instance.

    It initializes a model instance by parsing and validating input data
    from the `data` keyword arguments.

    Args:
        **data: The input data to initialize the model instance.

    Raises:
        ValidationError: If the object could not be validated.

    Note:
        The argument ``self`` is explicitly positional-only to allow
        ``self`` as a field name and data keyword argument.
    """
    # Tell pytest to hide this function from tracebacks
    __tracebackhide__ = True

    self.__pydantic_validator__.validate_python(data, self_instance=self)

SettingsDict

Bases: TypedDict

Plateforme application settings dictionary.

context instance-attribute

context: bool

Whether to set up and maintain the application context in the current thread when creating the instance. When enabled, the application context will be set to the current application being initialized, and won't require an explicit context manager. Defaults to True.

debug instance-attribute

debug: bool

Whether to run the application in debug mode. When debug mode is enabled, debug tracebacks will be returned on server and the application will automatically reload when changes are detected in the underlying code. Defaults to False.

secret_key instance-attribute

secret_key: SecretStr | str

The application secret key. If not provided, a random alphanumeric secret key marked as insecure will be generated. Please note that it must be kept secret and should not be shared, it's insecure to use a secret key in a public repository. Consider using an environment variable instead. Defaults to a random secret key.

title instance-attribute

title: str

The application human-readable title that is used to display the application verbose name and will be added to the generated OpenAPI, visible at '/docs'. When not provided, a random title will be generated. Defaults to a random title.

summary instance-attribute

summary: str | None

A short summary of the application. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

description instance-attribute

description: str | None

A description of the application. Supports Markdown (using CommonMark syntax). It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

version instance-attribute

version: str

The application version. It is used to define the version of the application, not the version of the OpenAPI specification or the version of the Plateforme framework being used. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to '0.1.0'.

contact instance-attribute

contact: ContactInfo | ContactInfoDict | str | None

The contact information for the application exposed API. It can be provided either as a string with the contact name and optionally an email address, or as a dictionary. The following fields will be added to the generated OpenAPI, visible at '/docs': - name (str): The name of the contact person or organization. If not provided, it defaults to an empty string. - url (str): An URL pointing to the contact information. It must be formatted as a valid URL. - email (str): The email address of the contact person or organization. It must be formatted as a valid email address. Defaults to None.

license instance-attribute

license: LicenseInfo | LicenseInfoDict | str | None

The license information for the application exposed API. It can be provided either as a string with the license name, or as a dictionary. The following fields will be added to the generated OpenAPI, visible at '/docs': - name (str): The license name used for the API. - identifier (str): An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0. - url (str): An URL to the license used for the API. This must be formatted as a valid URL. Defaults to None.

terms_of_service instance-attribute

terms_of_service: str | None

A URL to the Terms of Service for the application exposed API. It will be added to the generated OpenAPI, visible at '/docs'. Defaults to None.

language instance-attribute

language: str

The application language code. Defaults to 'en'.

timezone instance-attribute

timezone: str

The application time zone code. Defaults to 'UTC'.

auto_import_dependencies instance-attribute

auto_import_dependencies: bool

Whether to automatically import dependencies of the application packages. Auto-imported package dependencies are implemented with their default settings. Defaults to True.

auto_import_namespaces instance-attribute

auto_import_namespaces: bool

Whether to automatically import and create missing namespace configurations for packages within the application. Defaults to True.

namespaces instance-attribute

The application namespaces to load. Each namespace can be provided either as a string for the namespace name or a tuple with the namespace name and its settings. The namespace name is used to group package resources and services within the application to avoid name collisions. The default namespace uses the empty string as its name ''. The namespace settings are used to override the default namespace implementation configuration. Defaults to an empty list.

packages instance-attribute

The application packages to load. Each package can be provided either as a string for the package name or a tuple with the package name and its settings. The package name is used to load the package with its resources and services within the application. The package settings are used to override the default package implementation configuration. The default special package symbol $ is used to reference the application caller package and load its module resources and services. Defaults to a list with the special package symbol '$'.

api instance-attribute

The API settings. Defaults to the default API settings.

api_max_depth instance-attribute

api_max_depth: int

The maximum depth to walk through the resource path to collect manager methods from resource dependencies. It is used to generate the API routes for resources within the application. Defaults to 2.

api_max_selection instance-attribute

api_max_selection: int

The limit of resources to return for the API route selections. It is used when generating the API routes for resources within the application to avoid too many resources being returned. Defaults to 20.

database_engines instance-attribute

database_engines: (
    EngineMap | dict[str, Path | str] | Path | str
)

The application database engines. It accepts either: - A string with the database engine URL such as ':memory:' for an in-memory SQLite database, a path to a SQLite database file, or a database URL for other database engines. - A dictionary with the database engine URL for the default engine and other engines. Defaults to ':memory:'.

database_routers instance-attribute

database_routers: Sequence[str]

The application database routers. A list of either module names from which to import database routers, or fully qualified names of database routers. Defaults to an empty list.

logging instance-attribute

Whether to enable logging in the application. When enabled, the application will log messages to the configured handlers. It accepts either a boolean to enable or disable default logging settings or a dictionary with custom logging settings. Defaults to True.

deprecated instance-attribute

deprecated: bool | None

Whether the application is deprecated. Defaults to None.

Settings

Bases: BaseSettings

Plateforme application settings.

generate_secret_key

generate_secret_key(
    length: int = 32, secure: bool = False
) -> str

Generate a secure alphanumeric secret key of the given length.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def generate_secret_key(length: int = 32, secure: bool = False) -> str:
    """Generate a secure alphanumeric secret key of the given length."""
    import secrets

    characters = string.ascii_letters + string.digits
    key = ''.join(secrets.choice(characters) for _ in range(length))
    if not secure:
        return f'insecure={key}'
    return key

generate_seed_from_path

generate_seed_from_path(path: str | None = None) -> int

Generates a reproducible seed from a system path.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def generate_seed_from_path(path: str | None = None) -> int:
    """Generates a reproducible seed from a system path."""
    import hashlib
    import sys

    if path is None:
        path = sys.path[0] if sys.path else ''
    seed = int(hashlib.sha256(path.encode()).hexdigest(), 16)
    return seed

generate_title

generate_title() -> str

Generate a random title.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def generate_title() -> str:
    """Generate a random title."""
    from random import Random
    generator = Random(generate_seed_from_path())
    title_adjective: str = generator.choice(ADJECTIVES)
    title_noun: str = generator.choice([
        noun for noun in NOUNS if noun[0] != title_adjective[0]
    ])
    return f'{title_adjective} {title_noun}'

merge_settings

merge_settings(
    settings: Model,
    *others: BaseModel | None,
    **update: Any,
) -> Model

Merge multiple settings into a single settings instance.

It copies the provided settings model instance and merges other settings model instances into for matching fields. The last settings model instance has precedence over the previous ones. Additional settings can be provided as keyword arguments, where a DefaultPlaceholder can be used to set a default value for a field when no previous settings have set it.

Parameters:

Name Type Description Default
settings Model

The settings model instance to copy and use as a base.

required
*others BaseModel | None

The other settings model instances to merge into the base.

()
**update Any

Values to add/modify within the new model. Note that the integrity of the data is not validated when creating the new model. Data should be trusted or pre-validated in this case. Additionaly it can include DefaultPlaceholder values to set default values for settings model fields.

{}

Returns:

Type Description
Model

The merged settings model instance.

Raises:

Type Description
ValidationError

If the merged settings are invalid.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/settings.py
def merge_settings(
    settings: Model,
    *others: BaseModel | None,
    **update: Any,
) -> Model:
    """Merge multiple settings into a single settings instance.

    It copies the provided settings model instance and merges other settings
    model instances into for matching fields. The last settings model instance
    has precedence over the previous ones. Additional settings can be provided
    as keyword arguments, where a `DefaultPlaceholder` can be used to set a
    default value for a field when no previous settings have set it.

    Args:
        settings: The settings model instance to copy and use as a base.
        *others: The other settings model instances to merge into the base.
        **update: Values to add/modify within the new model. Note that the
            integrity of the data is not validated when creating the new model.
            Data should be trusted or pre-validated in this case. Additionaly
            it can include `DefaultPlaceholder` values to set default values
            for settings model fields.

    Returns:
        The merged settings model instance.

    Raises:
        ValidationError: If the merged settings are invalid.
    """
    # Create a new settings model instance
    data = settings.model_dump(exclude_defaults=True)

    # Merge other settings
    for other in others:
        if other is None:
            continue
        for key in other.model_fields_set:
            if key not in settings.model_fields:
                continue
            settings_field = settings.model_fields[key]
            other_field = other.model_fields[key]
            if settings_field.annotation == other_field.annotation:
                data[key] = getattr(other, key)

    # Update settings
    for key, value in update.items():
        if key not in settings.model_fields:
            continue
        if isinstance(value, DefaultPlaceholder):
            if key in data:
                continue
            data[key] = value.value
        else:
            data[key] = value

    # Validate settings
    return settings.model_construct(**data)

plateforme.core.loaders

This module provides utilities for managing loaders used in settings within the Plateforme framework.

LoaderInfo

LoaderInfo(name: str, *, static: bool = True)

Bases: Representation

Information about a loader.

This class is used to store information about an object that is loaded using a fullname. It is used to serialize and deserialize the object.

Attributes:

Name Type Description
name

The fullname of the object.

static

Whether the object was loaded statically.

Initialize the loader information.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def __init__(self, name: str, *, static: bool = True) -> None:
    """Initialize the loader information."""
    self.name = name
    self.static = static

Loader

Loader(type_: type[_T] = object)

Bases: Generic[_T]

A loader for objects.

This class is used to load objects from a fullname. It is used to serialize and deserialize the object.

Attributes:

Name Type Description
type_ type[_T]

The type of the object to load.

Initialize the loader.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def __init__(self, type_: type[_T] = object) -> None:  # type: ignore
    """Initialize the loader."""
    self.type_ = type_

serialize

serialize(
    obj: _T, info: SerializationInfo | None = None
) -> LoaderInfo | str

Serialize the loaded object.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def serialize(
    self,
    obj: _T,
    info: SerializationInfo | None = None,
) -> LoaderInfo | str:
    """Serialize the loaded object."""
    if info and info.mode == 'python':
        return obj
    if loader := getattr(obj, '__config_loader__', None):
        assert isinstance(loader, LoaderInfo)
        return loader.name

    raise ValueError(
        f"Cannot serialize object {obj!r} in JSON mode without a loader "
        f"information."
    )

validate

validate(obj: Any, *, strict: bool | None = None) -> _T

Validate and load an object.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def validate(
    self,
    obj: Any,
    *,
    strict: bool | None = None,
) -> _T:
    """Validate and load an object."""
    # Load object
    if isinstance(obj, (LoaderInfo, str)):
        loader = LoaderInfo(str(obj))
        instance = import_object(loader.name)
        if instance is self.type_:
            instance = instance()
        object.__setattr__(instance, '__config_loader__', loader)
    elif strict:
        raise ValueError(
            f"Cannot load object {obj!r} without a loader information."
        )
    else:
        instance = obj

    # Validate object instance
    if not self.validate_instance(instance, strict=strict):
        raise ValueError(
            f"Loaded object {instance!r} is not an instance of "
            f"{self.type_!r}."
        )
    return instance  # type: ignore[no-any-return]

validate_instance

validate_instance(
    obj: Any, *, strict: bool | None = None
) -> bool

Validate an object instance against the loader type.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/loaders.py
def validate_instance(
    self,
    obj: Any,
    *,
    strict: bool | None = None,
) -> bool:
    """Validate an object instance against the loader type."""
    origin = typing.get_origin(self.type_)
    if origin is None:
        return isinstance(obj, self.type_)
    if origin in (type, Type):
        args = typing.get_args(self.type_)
        return issubclass(obj, args[0])

    try:
        return isinstance(obj, origin)
    except TypeError:
        if strict:
            return False
    return True