Config (harp.config)

The Config (harp.config) module provides tools to configure Applications.

Applications are standard python packages that contains specific definitions to be able to register services and configure themselves. Every feature of Harp is built as an application, and you will want to write applications if you want to extend harp’s functionality for specific needs.

Contents

class Application[source]

Bases: object

__init__(*, on_bind=None, on_bound=None, on_ready=None, on_shutdown=None, settings_type=None, dependencies=None)[source]
Parameters:
defaults()[source]
normalize(settings)[source]
on_bind: Callable[[OnBindEvent], Awaitable[None]] = None

Placeholder for factory bind event, happening before the container is built. If set, it will be attached to the factory dispatcher automatically.

on_bound: Callable[[OnBoundEvent], Awaitable[None]] = None

Placeholder for factory bound event, happening after the container is built. If set, it will be attached to the factory dispatcher automatically.

on_ready: Callable[[OnReadyEvent], Awaitable[None]] = None

Placeholder for factory build event, happening after the kernel is built. If set, it will be attached to the factory dispatcher automatically.

on_shutdown: Callable[[OnShutdownEvent], Awaitable[None]] = None

Placeholder for factory dispose event, happening after the kernel is disposed. If set, it will be attached to the factory dispatcher automatically, in reverse order of appearance (first loaded application will be disposed last).

path: str | None = None

A placeholder for the source path of the application.

settings_type: Type = None

Type definition for configuration parsing.

class ApplicationsRegistry[source]

Bases: object

__init__(*, namespaces=None)[source]
Parameters:

namespaces (list[str] | None)

add(*names)[source]
aslist()[source]
defaults()[source]
get_application(name)[source]

Returns the application class for the given application name.

todo: add name/full_name attributes with raise if already set to different value ?

Parameters:

name (str)

Returns:

Return type:

Application

items()[source]
Return type:

ItemsView[str, Application]

keys()[source]
Return type:

KeysView[str]

register_events(dispatcher)[source]
Parameters:

dispatcher (IAsyncEventDispatcher)

register_services(container, config)[source]
Parameters:
remove(*names)[source]
resolve_name(spec)[source]
resolve_short_name(full_name)[source]
values()[source]
Return type:

ValuesView[Application]

namespaces = ['harp_apps']
class Configurable[source]

Bases: BaseConfigurable

A settings definition base.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[Dict[str, FieldInfo]] = {}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.

This replaces Model.__fields__ from Pydantic V1.

class ConfigurationBuilder[source]

Bases: ConfigurationBuilder

A builder class for assembling the global configuration settings for HARP from various sources.

This class extends config.ConfigurationBuilder, incorporating additional functionality specific to HARP, such as handling default applications and integrating with the ApplicationsRegistry. It supports adding configuration from files, environment variables, and direct values, with a focus on flexibility and ease of use.

Attributes:

_defaults (dict): Default values for the configuration, typically loaded from internal defaults or specified by the user. applications (ApplicationsRegistryType): An instance of ApplicationsRegistry or a subclass, managing the registration and configuration of HARP applications. applications_registry_type (type): The type of ApplicationsRegistry to use for managing applications.

Methods:

add_file(filename: str): Adds a single configuration file by its filename. add_files(filenames: Iterable[str]): Adds multiple configuration files by their filenames. add_values(values: dict): Adds configuration values directly from a dictionary. normalize(x: dict): Normalizes the configuration values, potentially transforming them based on application-specific logic. build() -> GlobalSettings: Constructs the final, aggregated configuration settings as a GlobalSettings instance. from_commandline_options(options): Class method to create an instance of ConfigurationBuilder from command line options. from_bytes(serialized: bytes, **kwargs) -> Self: Class method to create an instance of ConfigurationBuilder from serialized bytes.

The ConfigurationBuilder is central to the dynamic configuration system in HARP, allowing configurations to be built and modified in a flexible and intuitive manner.

Initializes a new instance of the ConfigurationBuilder.

Parameters:

default_values (dict, optional): A dictionary of default configuration values. Defaults to None. use_default_applications (bool, optional): Whether to automatically include default HARP applications in the configuration. Defaults to True.

__init__(default_values=None, /, *, use_default_applications=True)[source]

Initializes a new instance of the ConfigurationBuilder.

Parameters:

default_values (dict, optional): A dictionary of default configuration values. Defaults to None. use_default_applications (bool, optional): Whether to automatically include default HARP applications in the configuration. Defaults to True.

Return type:

None

async abuild_system()[source]
Return type:

System

add_file(filename)[source]

Adds a configuration file to the builder.

Parameters:

filename (str): The path to the configuration file to add.

Raises:

ValueError: If the file extension is not recognized.

Parameters:

filename (str)

add_files(filenames)[source]

Adds multiple configuration files to the builder.

Parameters:

filenames (Iterable[str]): An iterable of file paths to add.

Parameters:

filenames (Iterable[str])

add_values(values)[source]

Adds configuration values directly from a dictionary.

Parameters:

values (dict): A dictionary of configuration values to add.

Parameters:

values (dict)

build()[source]

Constructs the final, aggregated configuration settings as a GlobalSettings instance.

Returns:

GlobalSettings: The aggregated global settings derived from all added sources.

Return type:

GlobalSettings

create_application_registry()[source]
classmethod from_bytes(serialized, **kwargs)[source]

Creates an instance of ConfigurationBuilder from serialized bytes.

Parameters:

serialized (bytes): The serialized configuration data. **kwargs: Additional keyword arguments to pass to the constructor.

Returns:

ConfigurationBuilder: An instance of ConfigurationBuilder initialized with the deserialized configuration data.

Parameters:

serialized (bytes)

Return type:

Self

classmethod from_commandline_options(options)[source]

Creates an instance of ConfigurationBuilder from command line options.

Parameters:

options: The command line options to use for building the configuration.

Returns:

ConfigurationBuilder: An instance of ConfigurationBuilder configured according to the provided command line options.

Return type:

Self

normalize(x)[source]

Normalizes the configuration values, potentially transforming them based on application-specific logic.

Parameters:

x (dict): The configuration values to normalize.

Returns:

dict: The normalized configuration values.

Parameters:

x (dict)

class LazyService[source]

Bases: BaseConfigurable

A lazy service definition, that will be resolved at runtime.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

resolve(resolver, context)[source]

Resolve reference value in using the given resolver (callable) and resolution context.

model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[Dict[str, FieldInfo]] = {'type': FieldInfo(annotation=Union[str, list[str]], required=True, description='Reference to the service to resolve at runtime.')}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.

This replaces Model.__fields__ from Pydantic V1.

type: str | list[str]
class OnBindEvent[source]

Bases: Event

«Bind» event happens before the service container is resolved.

It is the right place to define services that may not be resolvable yet (because their dependencies may, or may not, be defined already).

__init__(container, settings)[source]
Parameters:
container: Container

Service container.

name = 'harp.config.bind'

Event name placeholder, will be set by dispatcher.

settings: GlobalSettings

Global settings.

class OnBoundEvent[source]

Bases: Event

«Bound» event happens after the service container is resolved, before the kernel creation.

It is the right place to setup things that needs the container to be resolved (thus, you get a provider instead of a container).

__init__(provider, resolver)[source]
Parameters:
name = 'harp.config.bound'

Event name placeholder, will be set by dispatcher.

provider: Services

Services provider.

resolver: ProxyControllerResolver

Proxy controller resolver.

class OnReadyEvent[source]

Bases: Event

«Ready» event happens after the asgi kernel is created, just before the application starts.

It is the right place to decorate the kernel with middlewares.

__init__(provider, asgi_app, binds)[source]
Parameters:
  • provider (Services)

  • asgi_app (Type[ASGI2Protocol] | Callable[[HTTPScope | WebSocketScope | LifespanScope, Callable[[], Awaitable[HTTPRequestEvent | HTTPDisconnectEvent | WebSocketConnectEvent | WebSocketReceiveEvent | WebSocketDisconnectEvent | LifespanStartupEvent | LifespanShutdownEvent]], Callable[[HTTPResponseStartEvent | HTTPResponseBodyEvent | HTTPResponseTrailersEvent | HTTPServerPushEvent | HTTPDisconnectEvent | WebSocketAcceptEvent | WebSocketSendEvent | WebSocketResponseStartEvent | WebSocketResponseBodyEvent | WebSocketCloseEvent | LifespanStartupCompleteEvent | LifespanStartupFailedEvent | LifespanShutdownCompleteEvent | LifespanShutdownFailedEvent], Awaitable[None]]], Awaitable[None]])

  • binds (list[Bind])

name = 'harp.config.ready'

Event name placeholder, will be set by dispatcher.

class OnShutdownEvent[source]

Bases: Event

«Shutdown» event happens when the application is stopping.

__init__(asgi_app, provider)[source]
Parameters:
  • asgi_app (Type[ASGI2Protocol] | Callable[[HTTPScope | WebSocketScope | LifespanScope, Callable[[], Awaitable[HTTPRequestEvent | HTTPDisconnectEvent | WebSocketConnectEvent | WebSocketReceiveEvent | WebSocketDisconnectEvent | LifespanStartupEvent | LifespanShutdownEvent]], Callable[[HTTPResponseStartEvent | HTTPResponseBodyEvent | HTTPResponseTrailersEvent | HTTPServerPushEvent | HTTPDisconnectEvent | WebSocketAcceptEvent | WebSocketSendEvent | WebSocketResponseStartEvent | WebSocketResponseBodyEvent | WebSocketCloseEvent | LifespanStartupCompleteEvent | LifespanStartupFailedEvent | LifespanShutdownCompleteEvent | LifespanShutdownFailedEvent], Awaitable[None]]], Awaitable[None]])

  • provider (Services)

name = 'harp.config.shutdown'

Event name placeholder, will be set by dispatcher.

class Service[source]

Bases: BaseConfigurable

A settings base class for service definitions.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

to_service_definition(name, lifestyle='singleton')[source]

Convert the service settings to a service definition.

Parameters:
  • name (str)

  • lifestyle (Literal['singleton', 'transient', 'scoped'] | None)

Return type:

ServiceDefinition

arguments: dict | None

Arguments for the service constructor, by name.

base: str | None

Base type for service definition. This is not usually the base interface that the service implements, and you should use the type field to override the actually instanciated type.

constructor: str | None

Constructor for service definition. If provided, will be used instead of the default constructor.

model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_config: ClassVar[ConfigDict] = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[Dict[str, FieldInfo]] = {'arguments': FieldInfo(annotation=Union[dict, NoneType], required=False, default_factory=dict, description='Arguments for the service constructor.'), 'base': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Base type for service definition.'), 'constructor': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Optional custom constructor for the service.'), 'type': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description='Type for service definition.')}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.

This replaces Model.__fields__ from Pydantic V1.

type: str | None

Type for service definition. This is the actual type that will be instanciated.

class Stateful[source]

Bases: BaseConfigurable, Generic[TSettings]

A base class for stateful objects that are related to a settings class. Usually, it’s used for live status of settings-defined objects, that may vary over time. It allows to separate the concerns of the imuatable, environment-provided settings, and the mutable, runtime-related state of the object.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

classmethod from_settings_dict(data)[source]
Parameters:

data (dict)

Return type:

Self

classmethod from_settings_kwargs(**kwargs)[source]
Return type:

Self

classmethod get_settings_type()[source]
Return type:

Type[Configurable]

model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}

A dictionary of computed field names and their corresponding ComputedFieldInfo objects.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[Dict[str, FieldInfo]] = {'settings': FieldInfo(annotation=TypeVar, required=True, repr=False)}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.

This replaces Model.__fields__ from Pydantic V1.

settings: Annotated[TSettings, FieldInfo(annotation=NoneType, required=True, repr=False)]
asdict(obj, /, *, secure=True, verbose=False, mode='json')[source]
Parameters:

mode (Literal['json', 'python'] | str)

Submodules