Library Reference

Hello module.

pydantic model oe_python_template_example.hello.Echo

Response model for echo endpoint.

Fields:
  • text (str)

field text: str [Required]

The echo

Constraints:
  • min_length = 1

class oe_python_template_example.hello.PageBuilder
static register_pages() None

Register pages.

class oe_python_template_example.hello.Service

Service of the hello module.

static echo(utterance: Utterance) Echo

Loudly echo utterance.

Parameters:

utterance (Utterance) – The utterance to echo.

Returns:

The loudly echoed utterance.

Return type:

Echo

Raises:

ValueError – If the utterance is empty or contains only whitespace.

get_hello_world() str

Get a hello world message.

Returns:

Hello world message.

Return type:

str

health() Health

Determine health of hello service.

Returns:

The health of the service.

Return type:

Health

info() dict[str, Any]

Determine info of this service.

Returns:

The info of this service.

Return type:

dict[str,Any]

pydantic settings oe_python_template_example.hello.Settings

Settings.

Show JSON schema
{
   "title": "Settings",
   "description": "Settings.",
   "type": "object",
   "properties": {
      "language": {
         "$ref": "#/$defs/Language",
         "default": "en_US",
         "description": "Language to use for output - defaults to US english."
      },
      "token": {
         "anyOf": [
            {
               "format": "password",
               "type": "string",
               "writeOnly": true
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Secret token of Hello module.",
         "title": "Token"
      }
   },
   "$defs": {
      "Language": {
         "description": "Supported languages.",
         "enum": [
            "de_DE",
            "en_US"
         ],
         "title": "Language",
         "type": "string"
      }
   }
}

Config:
  • extra: str = ignore

  • env_prefix: str = OE_PYTHON_TEMPLATE_EXAMPLE_HELLO_

  • env_file: list = [PosixPath(‘/home/docs/.oe_python_template_example/.env’), PosixPath(‘/home/docs/.oe_python_template_example/.env.local’), PosixPath(‘.env’), PosixPath(‘.env.local’)]

  • env_file_encoding: str = utf-8

Fields:
  • language (oe_python_template_example.hello._settings.Language)

  • token (pydantic.types.SecretStr | None)

field language: ')] = Language.US_ENGLISH

Language to use for output - defaults to US english.

field token: Annotated[SecretStr | None, BeforeValidator(func=strip_to_none_before_validator, json_schema_input_type=PydanticUndefined), PlainSerializer(func=serialize_sensitive_info, return_type=str, when_used=always), FieldInfo(annotation=NoneType, required=False, default=None, description='Secret token of Hello module.')] = None

Secret token of Hello module.

Constraints:
  • func = <function OpaqueSettings.serialize_sensitive_info at 0x7197ce9902c0>

  • json_schema_input_type = PydanticUndefined

  • return_type = <class ‘str’>

  • when_used = always

pydantic model oe_python_template_example.hello.Utterance

Model representing a text utterance.

Fields:
  • text (str)

field text: str [Required]

The utterance to echo back

Constraints:
  • min_length = 1

System module.

class oe_python_template_example.system.PageBuilder
static register_pages() None

Register pages.

class oe_python_template_example.system.Service

System service.

static div_by_zero() float

Divide by zero to trigger an error.

  • This function is used to validate error handling and instrumentation

    in the system.

Returns:

This function will raise a ZeroDivisionError before returning.

Return type:

float

health() Health

Determine aggregate health of the system.

  • Health exposed by implementations of BaseService in other

    modules is automatically included into the health tree.

  • See utils/_health.py:Health for an explanation of the health tree.

Returns:

The aggregate health of the system.

Return type:

Health

static info(include_environ: bool = False, filter_secrets: bool = True) dict[str, Any]

Get info about configuration of service.

  • Runtime information is automatically compiled.

  • Settings are automatically aggregated from all implementations of

    Pydantic BaseSettings in this package.

  • Info exposed by implementations of BaseService in other modules is

    automatically included into the info dict.

Returns:

Service configuration.

Return type:

dict[str, Any]

is_token_valid(token: str) bool

Check if the presented token is valid.

Returns:

True if the token is valid, False otherwise.

Return type:

bool

static sleep(seconds: int) None

Sleep for a given number of seconds.

  • This function is used to validate performance profiling in the system.

Parameters:

seconds (int) – Number of seconds to sleep.

pydantic settings oe_python_template_example.system.Settings

Settings.

Show JSON schema
{
   "title": "Settings",
   "description": "Settings.",
   "type": "object",
   "properties": {
      "token": {
         "anyOf": [
            {
               "format": "password",
               "type": "string",
               "writeOnly": true
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Secret token to present when performing sensitive operations such as retrieving info via webservice API",
         "title": "Token"
      }
   }
}

Config:
  • extra: str = ignore

  • env_prefix: str = OE_PYTHON_TEMPLATE_EXAMPLE_SYSTEM_

  • env_file: list = [PosixPath(‘/home/docs/.oe_python_template_example/.env’), PosixPath(‘/home/docs/.oe_python_template_example/.env.local’), PosixPath(‘.env’), PosixPath(‘.env.local’)]

  • env_file_encoding: str = utf-8

Fields:
  • token (pydantic.types.SecretStr | None)

field token: Annotated[SecretStr | None, PlainSerializer(func=serialize_sensitive_info, return_type=str, when_used=always), FieldInfo(annotation=NoneType, required=False, default=None, description='Secret token to present when performing sensitive operations such as retrieving info via webservice API')] = None

Secret token to present when performing sensitive operations such as retrieving info via webservice API

Constraints:
  • func = <function OpaqueSettings.serialize_sensitive_info at 0x7197ce9902c0>

  • return_type = <class ‘str’>

  • when_used = always

Utilities module.

class oe_python_template_example.utils.BasePageBuilder

Base class for all page builders.

abstractmethod static register_pages() None

Register pages.

class oe_python_template_example.utils.BaseService(settings_class: type[T] | None = None)

Base class for services.

abstractmethod health() Health

Get health of this service. Override in subclass.

abstractmethod info() dict[str, Any]

Get info of this service. Override in subclass.

key() str

Return the module name of the instance.

class oe_python_template_example.utils.GUILocalFilePicker(directory: str, *, upper_limit: str | EllipsisType | None = Ellipsis, multiple: bool = False, show_hidden_files: bool = False)

Local File Picker dialog class that lazy-loads NiceGUI dependencies.

static __new__(cls, directory: str, *, upper_limit: str | EllipsisType | None = Ellipsis, multiple: bool = False, show_hidden_files: bool = False) GUILocalFilePicker

Create a new instance with lazy-loaded dependencies.

Parameters:
  • directory – The directory to start in.

  • upper_limit – The directory to stop at. None for no limit, default is same as starting directory.

  • multiple – Whether to allow multiple files to be selected.

  • show_hidden_files – Whether to show hidden files.

Returns:

An instance of the dialog with lazy-loaded dependencies.

pydantic model oe_python_template_example.utils.Health

Represents the health status of a service with optional components and failure reasons.

  • A health object can have child components, i.e. health forms a tree.

  • Any node in the tree can set itself to DOWN. In this case the node is required

    to set the reason attribute. If reason is not set when DOWN, automatic model validation of the tree will fail.

  • DOWN’ness is propagated to parent health objects. I.e. the health of a parent

    node is automatically set to DOWN if any of its child components are DOWN. The child components leading to this will be listed in the reason.

  • The root of the health tree is computed in the system module. The health of other

    modules is automatically picked up by the system module.

Fields:
  • components (dict[str, oe_python_template_example.utils._health.Health])

  • reason (str | None)

  • status (oe_python_template_example.utils._health._HealthStatus)

Validators:
  • validate_health_state » all fields

field components: dict[str, Health] [Optional]
Validated by:
  • validate_health_state

field reason: str | None = None
Validated by:
  • validate_health_state

field status: _HealthStatus [Required]
Validated by:
  • validate_health_state

Code

alias of _HealthStatus

compute_health_from_components() Self

Recursively compute health status from components.

  • If health is already DOWN, it remains DOWN with its original reason.

  • If health is UP but any component is DOWN, health becomes DOWN with

    a reason listing all failed components.

Returns:

The updated health instance with computed status.

Return type:

Self

validator validate_health_state  »  all fields

Validate the health state and ensure consistency.

  • Compute overall health based on component health

  • Ensure UP status has no associated reason

  • Ensure DOWN status always has a reason

Returns:

The validated model instance with correct health status.

Return type:

Self

Raises:

ValueError – If validation fails due to inconsistency.

pydantic settings oe_python_template_example.utils.LogSettings

Settings for configuring logging behavior.

Show JSON schema
{
   "title": "LogSettings",
   "description": "Settings for configuring logging behavior.",
   "type": "object",
   "properties": {
      "level": {
         "default": "INFO",
         "description": "Logging level",
         "enum": [
            "CRITICAL",
            "ERROR",
            "WARNING",
            "INFO",
            "DEBUG"
         ],
         "title": "Level",
         "type": "string"
      },
      "file_enabled": {
         "default": false,
         "description": "Enable logging to file",
         "title": "File Enabled",
         "type": "boolean"
      },
      "file_name": {
         "default": "oe_python_template_example.log",
         "description": "Name of the log file",
         "title": "File Name",
         "type": "string"
      },
      "console_enabled": {
         "default": false,
         "description": "Enable logging to console",
         "title": "Console Enabled",
         "type": "boolean"
      }
   }
}

Config:
  • extra: str = ignore

  • env_prefix: str = OE_PYTHON_TEMPLATE_EXAMPLE_LOG_

  • env_file: list = [PosixPath(‘/home/docs/.oe_python_template_example/.env’), PosixPath(‘/home/docs/.oe_python_template_example/.env.local’), PosixPath(‘.env’), PosixPath(‘.env.local’)]

  • env_file_encoding: str = utf-8

Fields:
  • console_enabled (bool)

  • file_enabled (bool)

  • file_name (str)

  • level (Literal['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'])

field console_enabled: Annotated[bool, FieldInfo(annotation=NoneType, required=False, default=False, description='Enable logging to console')] = False

Enable logging to console

field file_enabled: Annotated[bool, FieldInfo(annotation=NoneType, required=False, default=False, description='Enable logging to file')] = False

Enable logging to file

field file_name: Annotated[str, AfterValidator(func=_validate_file_name), FieldInfo(annotation=NoneType, required=False, default='oe_python_template_example.log', description='Name of the log file')] = 'oe_python_template_example.log'

Name of the log file

Constraints:
  • func = <function _validate_file_name at 0x7197ce967c40>

field level: Annotated[Literal['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], FieldInfo(annotation=NoneType, required=False, default='INFO', description='Logging level')] = 'INFO'

Logging level

pydantic settings oe_python_template_example.utils.LogfireSettings

Configuration settings for Logfire integration.

Show JSON schema
{
   "title": "LogfireSettings",
   "description": "Configuration settings for Logfire integration.",
   "type": "object",
   "properties": {
      "token": {
         "anyOf": [
            {
               "format": "password",
               "type": "string",
               "writeOnly": true
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Logfire token. Leave empty to disable logfire.",
         "examples": [
            "YOUR_TOKEN"
         ],
         "title": "Token"
      },
      "instrument_system_metrics": {
         "default": false,
         "description": "Enable system metrics instrumentation",
         "title": "Instrument System Metrics",
         "type": "boolean"
      }
   }
}

Config:
  • extra: str = ignore

  • env_prefix: str = OE_PYTHON_TEMPLATE_EXAMPLE_LOGFIRE_

  • env_file: list = [PosixPath(‘/home/docs/.oe_python_template_example/.env’), PosixPath(‘/home/docs/.oe_python_template_example/.env.local’), PosixPath(‘.env’), PosixPath(‘.env.local’)]

  • env_file_encoding: str = utf-8

Fields:
  • instrument_system_metrics (bool)

  • token (pydantic.types.SecretStr | None)

field instrument_system_metrics: Annotated[bool, FieldInfo(annotation=NoneType, required=False, default=False, description='Enable system metrics instrumentation')] = False

Enable system metrics instrumentation

field token: Annotated[SecretStr | None, BeforeValidator(func=strip_to_none_before_validator, json_schema_input_type=PydanticUndefined), PlainSerializer(func=serialize_sensitive_info, return_type=str, when_used=always), FieldInfo(annotation=NoneType, required=False, default=None, description='Logfire token. Leave empty to disable logfire.', examples=['YOUR_TOKEN'])] = None

Logfire token. Leave empty to disable logfire.

Constraints:
  • func = <function OpaqueSettings.serialize_sensitive_info at 0x7197ce9902c0>

  • json_schema_input_type = PydanticUndefined

  • return_type = <class ‘str’>

  • when_used = always

pydantic settings oe_python_template_example.utils.OpaqueSettings

Show JSON schema
{
   "title": "OpaqueSettings",
   "type": "object",
   "properties": {},
   "additionalProperties": false
}

static serialize_sensitive_info(input_value: SecretStr, info: FieldSerializationInfo) str | None
pydantic model oe_python_template_example.utils.ProcessInfo

Information about the current process.

Fields:
  • parent (oe_python_template_example.utils._process.ParentProcessInfo)

  • pid (int)

  • project_root (str)

field parent: ParentProcessInfo [Required]
field pid: int [Required]
field project_root: str [Required]
pydantic settings oe_python_template_example.utils.SentrySettings

Configuration settings for Sentry integration.

Show JSON schema
{
   "title": "SentrySettings",
   "description": "Configuration settings for Sentry integration.",
   "type": "object",
   "properties": {
      "dsn": {
         "anyOf": [
            {
               "format": "password",
               "type": "string",
               "writeOnly": true
            },
            {
               "type": "null"
            }
         ],
         "default": null,
         "description": "Sentry DSN",
         "examples": [
            "https://SECRET@SECRET.ingest.de.sentry.io/SECRET"
         ],
         "title": "Dsn"
      },
      "debug": {
         "default": false,
         "description": "Debug (https://docs.sentry.io/platforms/python/configuration/options/)",
         "title": "Debug",
         "type": "boolean"
      },
      "send_default_pii": {
         "default": false,
         "description": "Send default personal identifiable information (https://docs.sentry.io/platforms/python/configuration/options/)",
         "title": "Send Default Pii",
         "type": "boolean"
      },
      "max_breadcrumbs": {
         "default": 50,
         "description": "Max breadcrumbs (https://docs.sentry.io/platforms/python/configuration/options/#max_breadcrumbs)",
         "minimum": 0,
         "title": "Max Breadcrumbs",
         "type": "integer"
      },
      "sample_rate": {
         "default": 1.0,
         "description": "Sample Rate (https://docs.sentry.io/platforms/python/configuration/sampling/#sampling-error-events)",
         "minimum": 0.0,
         "title": "Sample Rate",
         "type": "number"
      },
      "traces_sample_rate": {
         "default": 1.0,
         "description": "Traces Sample Rate (https://docs.sentry.io/platforms/python/configuration/sampling/#configuring-the-transaction-sample-rate)",
         "minimum": 0.0,
         "title": "Traces Sample Rate",
         "type": "number"
      },
      "profiles_sample_rate": {
         "default": 1.0,
         "description": "Traces Sample Rate (https://docs.sentry.io/platforms/python/tracing/#configure)",
         "minimum": 0.0,
         "title": "Profiles Sample Rate",
         "type": "number"
      }
   }
}

Config:
  • extra: str = ignore

  • env_prefix: str = OE_PYTHON_TEMPLATE_EXAMPLE_SENTRY_

  • env_file: list = [PosixPath(‘/home/docs/.oe_python_template_example/.env’), PosixPath(‘/home/docs/.oe_python_template_example/.env.local’), PosixPath(‘.env’), PosixPath(‘.env.local’)]

  • env_file_encoding: str = utf-8

Fields:
  • debug (bool)

  • dsn (pydantic.types.SecretStr | None)

  • max_breadcrumbs (int)

  • profiles_sample_rate (float)

  • sample_rate (float)

  • send_default_pii (bool)

  • traces_sample_rate (float)

field debug: Annotated[bool, FieldInfo(annotation=NoneType, required=False, default=False, description='Debug (https://docs.sentry.io/platforms/python/configuration/options/)')] = False

Debug (https://docs.sentry.io/platforms/python/configuration/options/)

field dsn: Annotated[SecretStr | None, BeforeValidator(func=strip_to_none_before_validator, json_schema_input_type=PydanticUndefined), AfterValidator(func=_validate_https_dsn), PlainSerializer(func=serialize_sensitive_info, return_type=str, when_used=always), FieldInfo(annotation=NoneType, required=False, default=None, description='Sentry DSN', examples=['https://SECRET@SECRET.ingest.de.sentry.io/SECRET'])] = None

Sentry DSN

Constraints:
  • func = <function OpaqueSettings.serialize_sensitive_info at 0x7197ce9902c0>

  • json_schema_input_type = PydanticUndefined

  • return_type = <class ‘str’>

  • when_used = always

field max_breadcrumbs: Annotated[int, FieldInfo(annotation=NoneType, required=False, default=50, description='Max breadcrumbs (https://docs.sentry.io/platforms/python/configuration/options/#max_breadcrumbs)', metadata=[Ge(ge=0)])] = 50

Max breadcrumbs (https://docs.sentry.io/platforms/python/configuration/options/#max_breadcrumbs)

Constraints:
  • ge = 0

field profiles_sample_rate: Annotated[float, FieldInfo(annotation=NoneType, required=False, default=1.0, description='Traces Sample Rate (https://docs.sentry.io/platforms/python/tracing/#configure)', metadata=[Ge(ge=0.0)])] = 1.0

Traces Sample Rate (https://docs.sentry.io/platforms/python/tracing/#configure)

Constraints:
  • ge = 0.0

field sample_rate: Annotated[float, FieldInfo(annotation=NoneType, required=False, default=1.0, description='Sample Rate (https://docs.sentry.io/platforms/python/configuration/sampling/#sampling-error-events)', metadata=[Ge(ge=0.0)])] = 1.0

Sample Rate (https://docs.sentry.io/platforms/python/configuration/sampling/#sampling-error-events)

Constraints:
  • ge = 0.0

field send_default_pii: Annotated[bool, FieldInfo(annotation=NoneType, required=False, default=False, description='Send default personal identifiable information (https://docs.sentry.io/platforms/python/configuration/options/)')] = False

Send default personal identifiable information (https://docs.sentry.io/platforms/python/configuration/options/)

field traces_sample_rate: Annotated[float, FieldInfo(annotation=NoneType, required=False, default=1.0, description='Traces Sample Rate (https://docs.sentry.io/platforms/python/configuration/sampling/#configuring-the-transaction-sample-rate)', metadata=[Ge(ge=0.0)])] = 1.0

Traces Sample Rate (https://docs.sentry.io/platforms/python/configuration/sampling/#configuring-the-transaction-sample-rate)

Constraints:
  • ge = 0.0

class oe_python_template_example.utils.VersionedAPIRouter(version: str, *args, **kwargs)

APIRouter with version attribute.

  • Use this class to create versioned routers for your FastAPI application

    that are automatically registered into the FastAPI app.

  • The version attribute is used to identify the version of the API

    that the router corresponds to.

  • See constants.por versions defined for this system.

static __new__(cls, version: str, *args, **kwargs) VersionedAPIRouter

Create a new instance with lazy-loaded dependencies.

Parameters:
  • version – The API version this router belongs to.

  • *args – Arguments to pass to the FastAPI APIRouter.

  • **kwargs – Keyword arguments to pass to the FastAPI APIRouter.

Returns:

An instance of VersionedAPIRouter with lazy-loaded dependencies.

classmethod get_instances() list[VersionedAPIRouter]

Get all created router instances.

Returns:

A list of all router instances created.

oe_python_template_example.utils.boot(modules_to_instrument: list[str]) None

Boot the application.

Parameters:
  • modules_to_instrument (list) – List of modules to be instrumented.

  • repository_url (str) – URL of the repository.

  • repository_root_path (str) – The root path of the repository. Default is the root path.

oe_python_template_example.utils.create_marimo_app() Any

Create a FastAPI app with marimo notebook server.

Returns:

FastAPI app with marimo notebook server.

Return type:

FastAPI

Raises:

ValueError – If the notebook directory does not exist.

oe_python_template_example.utils.get_logger(name: str | None) Logger

Get a logger instance with the given name or project name as default.

Parameters:

name (str) – The name for the logger. If None, uses project name.

Returns:

Configured logger instance.

Return type:

Logger

oe_python_template_example.utils.get_process_info() ProcessInfo

Get information about the current process and its parent.

Returns:

Object containing process information.

Return type:

ProcessInfo

oe_python_template_example.utils.gui_register_pages() None

Register pages.

This function is called by the GUI to register all pages.

oe_python_template_example.utils.gui_run(native: bool = True, show: bool = False, host: str | None = None, port: int | None = None, title: str = 'oe_python_template_example', icon: str = '', watch: bool = False, with_api: bool = False) None

Start the GUI.

Parameters:
  • native – Whether to run the GUI in native mode.

  • show – Whether to show the GUI.

  • host – Host to run the GUI on.

  • port – Port to run the GUI on.

  • title – Title of the GUI.

  • icon – Icon for the GUI.

  • watch – Whether to watch for changes and reload the GUI.

  • with_api – Whether to mount the API.

Raises:

ValueError – If with_notebook is True but notebook_path is None, or trying to run native within container.

oe_python_template_example.utils.load_settings(settings_class: type[T]) T

Load settings with error handling and nice formatting.

Parameters:

settings_class – The Pydantic settings class to instantiate

Returns:

Instance of the settings class

Return type:

Raises:

SystemExit – If settings validation fails

oe_python_template_example.utils.locate_implementations(_class: type[Any]) list[Any]

Dynamically discover all instances of some class.

Parameters:

_class (type[Any]) – Class to search for.

Returns:

List of discovered implementations of the given class.

Return type:

list[Any]

oe_python_template_example.utils.locate_subclasses(_class: type[Any]) list[Any]

Dynamically discover all classes that are subclasses of some type.

Parameters:

_class (type[Any]) – Parent class of subclasses to search for.

Returns:

List of discovered subclasses of the given class.

Return type:

list[type[Any]]

oe_python_template_example.utils.prepare_cli(cli: Typer, epilog: str) None

Dynamically locate, register and prepare subcommands.

Parameters:
  • cli (typer.Typer) – Typer instance

  • epilog (str) – Epilog to add

Example project scaffolded and kept up to date with OE Python Template (oe-python-template).