Resources
plateforme.core.resources
This module provides utilities for managing resources within the Plateforme framework's. It integrates with other core components of the framework, such as model validation and serialization, database interaction, and API routing.
The BaseResource
class is the foundational base for all resources within the
framework. It provides a common interface for defining resources and managing
their lifecycle. Resources are used to represent entities within the system,
such as users, products, or orders. They are used to define the structure of
the data, the business logic, and the API endpoints.
Note
See also the Field
function for more information on modeling features.
Resource
module-attribute
Resource = TypeVar('Resource', bound='BaseResource')
A type variable for a resource class.
ResourceType
module-attribute
ResourceType = Type['BaseResource']
A type alias for a resource class.
ResourceFieldInfo
module-attribute
ResourceFieldInfo = FieldInfo['BaseResource']
A type alias for a resource field information.
ResourceIndex
Bases: TypedDict
A configuration dictionary for defining indexes on resource fields.
name
instance-attribute
name: str
The name of the index. It can be used to customize the generated index name using the index registy naming convention. Defaults to the snake-cased concatenation of the resource alias and specified field aliases.
aliases
instance-attribute
The required resource field aliases to include in the index. The field aliases must be defined in the underlying resource model.
ResourceConfigDict
Bases: BaseModelConfigDict
A resource class configuration dictionary.
alias
instance-attribute
alias: str
The alias name of the model. It must adhere to a specific ALIAS
pattern as defined in the framework's regular expressions repository. It is
inferred from the snake case version of the resolved model identifier.
slug
instance-attribute
slug: str
The slug name of the model. It must adhere to a specific SLUG
pattern as defined in the framework's regular expressions repository. It is
inferred from the pluralized kebab case version of the model identifier.
title
instance-attribute
title: str
The human-readable name of the model. It must adhere to a specific
TITLE
pattern as defined in the framework's regular expressions
repository. It is inferred from the titleized version of the model
identifier.
str_to_lower
instance-attribute
str_to_lower: bool
Whether to convert strings to lowercase. Defaults to False
.
str_to_upper
instance-attribute
str_to_upper: bool
Whether to convert strings to uppercase. Defaults to False
.
str_strip_whitespace
instance-attribute
str_strip_whitespace: bool
Whether to strip whitespace from strings. Defaults to False
.
str_min_length
instance-attribute
str_min_length: int
The minimum length for strings. Defaults to None
.
str_max_length
instance-attribute
str_max_length: int | None
The maximum length for strings. Defaults to None
.
populate_by_name
instance-attribute
populate_by_name: bool
Whether to populate fields by name. Defaults to False
.
use_enum_values
instance-attribute
use_enum_values: bool
Whether to use enum values. Defaults to False
.
validate_assignment
instance-attribute
validate_assignment: bool
Whether to validate assignments. Defaults to False
.
arbitrary_types_allowed
instance-attribute
arbitrary_types_allowed: bool
Whether to allow arbitrary types. Defaults to False
.
from_attributes
instance-attribute
from_attributes: bool
Whether to set attributes from the configuration.
Defaults to False
.
loc_by_alias
instance-attribute
loc_by_alias: bool
Whether to use the alias for error loc
s. Defaults to True
.
alias_generator
instance-attribute
alias_generator: (
Callable[[str], str] | AliasGenerator | None
)
A callable or alias generator to create aliases for the model.
Defaults to None
.
ignored_types
instance-attribute
A tuple of types to ignore. Defaults to an empty tuple.
allow_inf_nan
instance-attribute
allow_inf_nan: bool
Whether to allow infinity and NaN. Defaults to True
.
json_schema_extra
instance-attribute
json_schema_extra: JsonSchemaExtraCallable | None
Dictionary of extra JSON schema properties. Defaults to None
.
json_encoders
instance-attribute
json_encoders: dict[type[object], JsonEncoder] | None
A dictionary of custom JSON encoders for specific types.
Defaults to None
.
revalidate_instances
instance-attribute
revalidate_instances: Literal[
"always", "never", "subclass-instances"
]
When and how to revalidate models and dataclasses during validation.
Defaults to never
.
ser_json_timedelta
instance-attribute
ser_json_timedelta: Literal['iso8601', 'float']
The format of JSON serialized timedeltas. Defaults to iso8601
.
ser_json_bytes
instance-attribute
ser_json_bytes: Literal['utf8', 'base64']
The encoding of JSON serialized bytes. Defaults to utf8
.
ser_json_inf_nan
instance-attribute
ser_json_inf_nan: Literal['null', 'constants']
The encoding of JSON serialized infinity and NaN float values. Accepts
the string values of 'null'
and 'constants'
.
Defaults to 'null'
.
validate_default
instance-attribute
validate_default: bool
Whether to validate default values during validation.
Defaults to False
.
validate_return
instance-attribute
validate_return: bool
Whether to validate return values during validation.
Defaults to False
.
protected_namespaces
instance-attribute
A tuple of strings that prevent models to have field which conflict with
them. The provided namespaces are added to the internally forbidden and
protected ones, model_
, resource_
, and service_
.
Defaults to an empty tuple.
hide_input_in_errors
instance-attribute
hide_input_in_errors: bool
Whether to hide inputs when printing errors. Defaults to False
.
plugin_settings
instance-attribute
A dictionary of settings for plugins. Defaults to None
.
schema_generator
instance-attribute
A custom core schema generator class to use when generating JSON
schemas. Defaults to None
.
json_schema_serialization_defaults_required
instance-attribute
json_schema_serialization_defaults_required: bool
Whether fields with default values should be marked as required in the
serialization schema. Defaults to False
.
json_schema_mode_override
instance-attribute
json_schema_mode_override: (
Literal["validation", "serialization"] | None
)
If not None
, the specified mode will be used to generate the JSON
schema regardless of what mode
was passed to the function call.
Defaults to None
.
coerce_numbers_to_str
instance-attribute
coerce_numbers_to_str: bool
If True
, enables automatic coercion of any Number
type to str
in
lax
(non-strict) mode. Defaults to False
.
regex_engine
instance-attribute
regex_engine: Literal['rust-regex', 'python-re']
The regex engine to use for pattern validation.
Defaults to rust-regex
.
validation_error_cause
instance-attribute
validation_error_cause: bool
If True
, Python exceptions that were part of a validation failure
will be shown as an exception group as a cause. Can be useful for
debugging. Defaults to False
.
use_attribute_docstrings
instance-attribute
use_attribute_docstrings: bool
Whether docstrings of attributes should be used for field descriptions.
Defaults to False
.
cache_strings
instance-attribute
Whether to cache strings to avoid constructing new Python objects.
Enabling this setting should significantly improve validation performance
while increasing memory usage slightly.
- True
or 'all'
(default): Cache all strings
- 'keys'
: Cache only dictionary keys
- False
or 'none'
: No caching
Defaults to True
.
tags
instance-attribute
A list of tags to associate with the resource. Tags are used to group
resources and provide additional metadata. It will be added to the
generated OpenAPI, visible at /docs
. If not provided, the resource slug
will be used as the default tag. Defaults to None
.
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 API routes.
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
.
id_strategy
instance-attribute
id_strategy: Literal['auto', 'manual', 'hybrid']
The identifier strategy to use for the resource. It defines how the
identifier is generated for the resource and can be set to one of the
following values:
- auto
: Enforce automatic generation of the resource identifier.
- manual
: Enforce manual specification of the resource identifier.
- hybrid
: Allow both automatic and manual generation of the resource
identifier.
Defaults to auto
.
id_type
instance-attribute
id_type: Literal['integer', 'uuid']
The identifier type to use for the resource. It defines the data type of
the resource identifier and can be set to one of the following values:
- integer
: Use an integer data type engine for the resource identifier.
- uuid
: Use a UUID data type engine for the resource identifier.
Defaults to integer
.
mapper_args
instance-attribute
A dictionary of additional arguments to pass to the resource declarative
mapper during the resource configuration, i.e. the dictionary of arguments
to add to the __mapper_args__
attribute of the resource class.
Defaults to an empty dictionary.
use_single_table_inheritance
instance-attribute
use_single_table_inheritance: bool
It defines the inheritance design pattern to use for database ORM.
Defaults to False
, using joined table inheritance with separate tables
for parent and child classes linked by a foreign key. This approach is
generally preferred for its normalization benefits. Setting this to
True
enables single table inheritance, creating a single table for both
parent and child classes with a discriminator column.
Note
Single table inheritance can lead to sparse tables and may impact performance for large and complex hierarchies.
indexes
instance-attribute
indexes: Sequence[ResourceIndex | set[str]]
A sequence or list of resource indexes configurations that define
indexing for resource model fields. An index is defined either as a set of
field aliases or as a dictionary with the following keys:
- aliases
: A tuple of strings representing the resource field aliases
to include in the index.
- unique
: Whether the index is unique. Defaults to True
.
Defaults to an empty sequence.
services
instance-attribute
services: Sequence[BaseService | EllipsisType | ServiceType]
A sequence of services to bind to the resource. The services are used to
define the business logic and data access methods for the resource. The
services can be defined as instances of BaseService
or as service
types. The ellipsis ...
can be used to insert all services from the
parent resource. Defaults to an empty sequence.
specs
instance-attribute
A sequence of specifications to apply to the resource. The specifications are used to define additional resource configurations, schemas, and behaviors. All the specifications from the parent resource are merged with the provided configuration, .i.e. a child resource must inherit all the specifications from the parent resource. Defaults to an empty sequence.
deprecated
instance-attribute
deprecated: bool | None
A flag indicating whether the resource is deprecated.
Defaults to None
.
ResourceConfig
ResourceConfig(
__owner: Any | None = None,
__defaults: dict[str, Any] | None = None,
__partial_init: bool = False,
/,
**data: Any,
)
Bases: ModelConfig
A resource class configuration.
Initialize the configuration class with the given data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__owner
|
Any | None
|
The owner of the configuration instance. It can be any
object or type that uses the configuration instance.
Defaults to |
None
|
__defaults
|
dict[str, Any] | None
|
The default values to initialize the configuration
instance with. Defaults to |
None
|
__partial_init
|
bool
|
Flag indicating whether to partially initialize
the configuration instance. Defaults to |
False
|
**data
|
Any
|
The data as keyword arguments to initialize the configuration instance with. |
{}
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
stub
class-attribute
instance-attribute
stub: bool = ConfigField(
default=False, frozen=True, init=False
)
Whether the model is a stub model. This is set to True
when a
collected bare model has a final stub no-operation statement.
Defaults to False
.
alias
class-attribute
instance-attribute
alias: str = Deferred
The alias name of the model. It must adhere to a specific ALIAS
pattern as defined in the framework's regular expressions repository. It is
inferred from the snake case version of the resolved model identifier.
slug
class-attribute
instance-attribute
slug: str = Deferred
The slug name of the model. It must adhere to a specific SLUG
pattern as defined in the framework's regular expressions repository. It is
inferred from the pluralized kebab case version of the model identifier.
title
class-attribute
instance-attribute
The human-readable name of the model. It must adhere to a specific
TITLE
pattern as defined in the framework's regular expressions
repository. It is inferred from the titleized version of the model
identifier.
str_to_lower
class-attribute
instance-attribute
Whether to convert strings to lowercase. Defaults to False
.
str_to_upper
class-attribute
instance-attribute
Whether to convert strings to uppercase. Defaults to False
.
str_strip_whitespace
class-attribute
instance-attribute
Whether to strip whitespace from strings. Defaults to False
.
str_min_length
class-attribute
instance-attribute
The minimum length for strings. Defaults to None
.
str_max_length
class-attribute
instance-attribute
The maximum length for strings. Defaults to None
.
frozen
class-attribute
instance-attribute
Whether to freeze the configuration. Defaults to False
.
populate_by_name
class-attribute
instance-attribute
Whether to populate fields by name. Defaults to False
.
use_enum_values
class-attribute
instance-attribute
Whether to use enum values. Defaults to False
.
validate_assignment
class-attribute
instance-attribute
Whether to validate assignments. Defaults to False
.
arbitrary_types_allowed
class-attribute
instance-attribute
Whether to allow arbitrary types. Defaults to False
.
from_attributes
class-attribute
instance-attribute
Whether to set attributes from the configuration.
Defaults to False
.
loc_by_alias
class-attribute
instance-attribute
Whether to use the alias for error loc
s. Defaults to True
.
alias_generator
class-attribute
instance-attribute
alias_generator: Annotated[
Callable[[str], str] | AliasGenerator | None, pydantic
] = to_name_case
A callable or alias generator to create aliases for the model.
Defaults to None
.
ignored_types
class-attribute
instance-attribute
A tuple of types to ignore. Defaults to an empty tuple.
allow_inf_nan
class-attribute
instance-attribute
Whether to allow infinity and NaN. Defaults to True
.
json_schema_extra
class-attribute
instance-attribute
json_schema_extra: Annotated[
JsonSchemaExtraCallable | None, pydantic
] = None
Dictionary of extra JSON schema properties. Defaults to None
.
json_encoders
class-attribute
instance-attribute
json_encoders: Annotated[
dict[type[object], JsonEncoder] | None, pydantic
] = None
A dictionary of custom JSON encoders for specific types.
Defaults to None
.
strict
class-attribute
instance-attribute
Whether to make the configuration strict. Defaults to False
.
revalidate_instances
class-attribute
instance-attribute
revalidate_instances: Annotated[
Literal["always", "never", "subclass-instances"],
pydantic,
] = "never"
When and how to revalidate models and dataclasses during validation.
Defaults to never
.
ser_json_timedelta
class-attribute
instance-attribute
The format of JSON serialized timedeltas. Defaults to iso8601
.
ser_json_bytes
class-attribute
instance-attribute
The encoding of JSON serialized bytes. Defaults to utf8
.
ser_json_inf_nan
class-attribute
instance-attribute
The encoding of JSON serialized infinity and NaN float values. Accepts
the string values of 'null'
and 'constants'
.
Defaults to 'null'
.
validate_default
class-attribute
instance-attribute
Whether to validate default values during validation.
Defaults to False
.
validate_return
class-attribute
instance-attribute
Whether to validate return values during validation.
Defaults to False
.
protected_namespaces
class-attribute
instance-attribute
A tuple of strings that prevent models to have field which conflict with
them. The provided namespaces are added to the internally forbidden and
protected ones, model_
, resource_
, and service_
.
Defaults to an empty tuple.
hide_input_in_errors
class-attribute
instance-attribute
Whether to hide inputs when printing errors. Defaults to False
.
plugin_settings
class-attribute
instance-attribute
A dictionary of settings for plugins. Defaults to None
.
schema_generator
class-attribute
instance-attribute
A custom core schema generator class to use when generating JSON
schemas. Defaults to None
.
json_schema_serialization_defaults_required
class-attribute
instance-attribute
Whether fields with default values should be marked as required in the
serialization schema. Defaults to False
.
json_schema_mode_override
class-attribute
instance-attribute
json_schema_mode_override: Annotated[
Literal["validation", "serialization"] | None, pydantic
] = None
If not None
, the specified mode will be used to generate the JSON
schema regardless of what mode
was passed to the function call.
Defaults to None
.
coerce_numbers_to_str
class-attribute
instance-attribute
If True
, enables automatic coercion of any Number
type to str
in
lax
(non-strict) mode. Defaults to False
.
regex_engine
class-attribute
instance-attribute
The regex engine to use for pattern validation.
Defaults to rust-regex
.
validation_error_cause
class-attribute
instance-attribute
If True
, Python exceptions that were part of a validation failure
will be shown as an exception group as a cause. Can be useful for
debugging. Defaults to False
.
use_attribute_docstrings
class-attribute
instance-attribute
Whether docstrings of attributes should be used for field descriptions.
Defaults to False
.
cache_strings
class-attribute
instance-attribute
Whether to cache strings to avoid constructing new Python objects.
Enabling this setting should significantly improve validation performance
while increasing memory usage slightly.
- True
or 'all'
(default): Cache all strings
- 'keys'
: Cache only dictionary keys
- False
or 'none'
: No caching
Defaults to True
.
type_
class-attribute
instance-attribute
type_: str = ConfigField(
default="resource", frozen=True, init=False
)
The configuration owner type set to resource
. It is a protected
field that is typically used with check_config
to validate an object type
without using isinstance
in order to avoid circular imports.
extra
class-attribute
instance-attribute
extra: Annotated[
Literal["allow", "ignore", "forbid"], pydantic
] = ConfigField(default="forbid", frozen=True, init=False)
Extra values are not allowed within a resource instance. This attribute
is protected and will initialize to its default value forbid
.
defer_build
class-attribute
instance-attribute
defer_build: Annotated[bool, pydantic] = ConfigField(
default=True, frozen=True, init=False
)
Defer building is not allowed for resource instances. This attribute is
protected and will initialize to its default value True
.
tags
class-attribute
instance-attribute
A list of tags to associate with the resource. Tags are used to group
resources and provide additional metadata. It will be added to the
generated OpenAPI, visible at /docs
. If not provided, the resource slug
will be used as the default tag. Defaults to None
.
api_max_depth
class-attribute
instance-attribute
api_max_depth: int = 2
The maximum depth to walk through the resource path to collect manager
methods from resource dependencies. It is used to generate API routes.
Defaults to 2
.
api_max_selection
class-attribute
instance-attribute
api_max_selection: int = 20
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
.
id_strategy
class-attribute
instance-attribute
id_strategy: Literal['auto', 'manual', 'hybrid'] = 'auto'
The identifier strategy to use for the resource. It defines how the
identifier is generated for the resource and can be set to one of the
following values:
- auto
: Enforce automatic generation of the resource identifier.
- manual
: Enforce manual specification of the resource identifier.
- hybrid
: Allow both automatic and manual generation of the resource
identifier.
Defaults to auto
.
id_type
class-attribute
instance-attribute
id_type: Literal['integer', 'uuid'] = 'integer'
The identifier type to use for the resource. It defines the data type of
the resource identifier and can be set to one of the following values:
- integer
: Use an integer data type engine for the resource identifier.
- uuid
: Use a UUID data type engine for the resource identifier.
Defaults to integer
.
mapper_args
class-attribute
instance-attribute
A dictionary of additional arguments to pass to the resource declarative
mapper during the resource configuration, i.e. the dictionary of arguments
to add to the __mapper_args__
attribute of the resource class.
Defaults to an empty dictionary.
use_single_table_inheritance
class-attribute
instance-attribute
use_single_table_inheritance: bool = False
It defines the inheritance design pattern to use for database ORM.
Defaults to False
, using joined table inheritance with separate tables
for parent and child classes linked by a foreign key. This approach is
generally preferred for its normalization benefits. Setting this to
True
enables single table inheritance, creating a single table for both
parent and child classes with a discriminator column.
Note
Single table inheritance can lead to sparse tables and may impact performance for large and complex hierarchies.
indexes
class-attribute
instance-attribute
indexes: tuple[ResourceIndex, ...] = ()
A tuple of resource indexes configurations that define indexing for
resource model fields. An index is defined as a dictionary with the
following keys:
- aliases
: A tuple of strings representing the resource field aliases
to include in the index.
- unique
: Whether the index is unique. Defaults to True
.
Defaults to an empty tuple.
services
class-attribute
instance-attribute
services: tuple[
BaseService | EllipsisType | ServiceType, ...
] = ()
A tuple of services to bind to the resource. The services are used to
define the business logic and data access methods for the resource. The
services can be defined as instances of BaseService
or as service
types. The ellipsis ...
can be used to insert all services from the
parent resource. Defaults to an empty tuple.
specs
class-attribute
instance-attribute
A tuple of specifications to apply to the resource. The specifications are used to define additional resource configurations, schemas, and behaviors. All the specifications from the parent resource are merged with the provided configuration, .i.e. a child resource must inherit all the specifications from the parent resource. Defaults to an empty tuple.
deprecated
class-attribute
instance-attribute
deprecated: bool | None = None
A flag indicating whether the resource is deprecated.
Defaults to None
.
id_autoincrement
property
Whether the resource identifier is autoincremented.
id_engine
property
id_engine: type[IntegerEngine | UuidEngine[UUID4]]
The identifier engine to use for the resource.
create
classmethod
create(
owner: Any | None = None,
defaults: dict[str, Any] | None = None,
partial_init: bool = False,
*,
data: dict[str, Any] | None = None,
) -> Self
Create a new configuration instance.
This method is typically used internally to create a new configuration
class with a specific owner and partial initialization flag. It is an
alternative to the __init__
method for creating a new configuration
instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
owner
|
Any | None
|
The owner of the configuration instance. |
None
|
defaults
|
dict[str, Any] | None
|
The default values to initialize the configuration
instance with. Defaults to |
None
|
partial_init
|
bool
|
Flag indicating whether to partially initialize the
configuration instance. Defaults to |
False
|
data
|
dict[str, Any] | None
|
The data to initialize the configuration instance with.
Defaults to |
None
|
Returns:
Type | Description |
---|---|
Self
|
The new configuration instance created. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
from_meta
classmethod
from_meta(
owner: type[Any],
bases: tuple[type, ...],
namespace: dict[str, Any],
/,
config_attr: str = "__config__",
partial_init: bool = False,
data: dict[str, Any] | None = None,
) -> Self
Create a new configuration instance from a class constructor.
This method is typically used internally to create a new configuration class from the meta configuration of a model, package, resource, or service. It merges the configuration of the given bases, the namespace, and the keyword arguments to create a new configuration class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
owner
|
type[Any]
|
The owner of the configuration instance. It should be the class that is being created from the meta configuration. |
required |
bases
|
tuple[type, ...]
|
The configurable base classes to merge. |
required |
namespace
|
dict[str, Any]
|
The configurable namespace to merge. |
required |
config_attr
|
str
|
The configurable attribute name used to extract the
configuration dictionary from the bases and the namespace of
the configurable class. Defaults to |
'__config__'
|
partial_init
|
bool
|
Flag indicating whether to partially initialize the
configuration instance. Defaults to |
False
|
data
|
dict[str, Any] | None
|
The data to initialize the configuration instance with.
Defaults to |
None
|
Returns:
Type | Description |
---|---|
Self
|
The new configuration instance created from the given meta |
Self
|
configuration. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
validate
Validate the configuration instance.
It post-initializes the configuration instance, checks for any missing required fields and validates the assignments of the configuration values based on the configuration fields information and the current validation context. This is performed automatically upon initialization of the configuration instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict
|
bool | None
|
Whether to enforce strict validation. Defaults to |
None
|
context
|
dict[str, Any] | None
|
The context to use for validation. Defaults to |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If the configuration instance has undefined values for required fields. |
ValidationError
|
If the assignment of a value is invalid based on the configuration fields information and the current validation context. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
context
staticmethod
Context manager for the configuration instance.
If the frozen mutation flag is not specified, the current frozen
mutation flag is used if available, otherwise it defaults to False
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
allow_mutation
|
bool | None
|
Flag indicating whether to allow frozen mutation
of the configuration instance. When set to |
None
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
clear
copy
copy() -> Self
Return a shallow copy of the configuration dictionary.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
merge
Merge the configuration with other configurations.
It merges the configuration with the provided configuration instances
or dictionaries. The precedence of the rightmost configuration is
higher than the leftmost configuration. This can be changed by setting
the setdefault
argument to True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*configs
|
Self | dict[str, Any]
|
The configuration instances or dictionaries to merge with the target configuration dictionary. |
()
|
setdefault
|
bool
|
Flag indicating whether to set the default values for
the configuration keys if they are not already set.
This modifies the behavior of the merge operation, making the
precedence of the leftmost configuration higher than the
rightmost configuration.
Defaults to |
False
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
check
check(
key: str,
*,
scope: Literal["all", "default", "set"] = "all",
raise_errors: bool = True,
) -> bool
Check if the configuration key exists in the given scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The configuration key to check for. |
required |
scope
|
Literal['all', 'default', 'set']
|
The scope to check for the configuration key. It can be
either |
'all'
|
raise_errors
|
bool
|
Flag indicating whether to raise an error if the
configuration key is not defined for the configuration wrapper.
Defaults to |
True
|
Returns:
Type | Description |
---|---|
bool
|
A boolean indicating whether the configuration key exists in the |
bool
|
specified scope. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
entries
entries(
*,
scope: Literal["all", "default", "set"] = "all",
default_mode: Literal[
"preserve", "unwrap", "wrap"
] = "unwrap",
include_keys: Iterable[str] | None = None,
exclude_keys: Iterable[str] | None = None,
include_metadata: Iterable[Any] | None = None,
exclude_metadata: Iterable[Any] | None = None,
) -> dict[str, Any]
Return the configuration dictionary.
It returns the configuration dictionary based on the specified scope, and keys and extra information to filter the configuration dictionary entries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scope
|
Literal['all', 'default', 'set']
|
The scope of the configuration dictionary to return. It can
be either |
'all'
|
default_mode
|
Literal['preserve', 'unwrap', 'wrap']
|
The default mode to use when returning a default
entry from the configuration dictionary. It can be either
|
'unwrap'
|
include_keys
|
Iterable[str] | None
|
The keys to include from the configuration dictionary
entries. Defaults to |
None
|
exclude_keys
|
Iterable[str] | None
|
The keys to exclude from the configuration dictionary
entries. Defaults to |
None
|
include_metadata
|
Iterable[Any] | None
|
The metadata information to include from the
configuration dictionary entries. Defaults to |
None
|
exclude_metadata
|
Iterable[Any] | None
|
The metadata information to exclude from the
configuration dictionary entries. Defaults to |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A dictionary containing the configuration entries based on the |
dict[str, Any]
|
specified scope and extra information. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 |
|
keys
values
values() -> ValuesView[Any]
items
get
get(
key: str,
default: Any = Undefined,
*,
default_mode: Literal[
"preserve", "unwrap", "wrap"
] = "unwrap",
) -> Any
Get the value for the specified key if set otherwise the default.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The configuration key to get the value for. |
required |
default
|
Any
|
The default value to return if the key is not set. |
Undefined
|
default_mode
|
Literal['preserve', 'unwrap', 'wrap']
|
The default mode to use when returning a default
value from the configuration dictionary. It can be either
|
'unwrap'
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
pop
pop(
key: str,
default: Any = Undefined,
*,
default_mode: Literal[
"preserve", "unwrap", "wrap"
] = "unwrap",
) -> Any
Pop the specified key if set and return its corresponding value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The configuration key to pop the value for. |
required |
default
|
Any
|
The default value to return if the key is not set. |
Undefined
|
default_mode
|
Literal['preserve', 'unwrap', 'wrap']
|
The default mode to use when returning a default
value from the configuration dictionary. It can be either
|
'unwrap'
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
getdefault
Get the default value for the specified key.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The configuration key to get the default value for. |
required |
mode
|
Literal['preserve', 'unwrap', 'wrap']
|
The mode to use when returning the default value. It can be
either |
'unwrap'
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
setdefault
Set the default value for the specified key.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The configuration key to set the default value for. |
required |
default
|
Any
|
The default value to set for the key. |
required |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
update
Update the config dictionary with new data.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
post_init
Post-initialization steps for the resource configuration.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
|
ResourceDict
A custom dictionary class for the resource instance.
Initialize a new resource dictionary with the provided model.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
clear
copy
copy() -> Self
keys
values
values() -> ValuesView[Any]
items
get
Get the value for the specified key.
pop
Pop the specified key from the inner dictionary.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
setdefault
Set the default value for the specified key if not set.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
update
Update the config dictionary with new data.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
ResourceNode
ResourceNode(
resource: type[Resource],
accessor: ResourceFieldInfo | None = None,
)
A resource node within the resources graph.
The resource node represents a segment
within the resources graph. It
is associated with a specific resource and a linked field accessor. The
node is used to build resource paths and navigate the resources graph.
Attributes:
Name | Type | Description |
---|---|---|
resource |
The resource associated with the node. |
|
accessor |
The linked field accessor associated with the node. |
Note
The identifiers generated from the unique indexes of the resource are used to identify a specific resource instance within this node. Thus, it can be used within a resource path to navigate the resources graph.
Initialize a new resource node.
It initializes a new resource node with the provided resource and linked field accessor. It serves as a building block for constructing resource paths and navigating the resources graph.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[Resource]
|
The resource associated with the node. |
required |
accessor
|
ResourceFieldInfo | None
|
The linked field accessor associated with the node. |
None
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
backref
property
backref: ResourceFieldInfo | None
The accessor association backref of the resource node.
ResourcePathInfo
dataclass
A resource path information class.
It provides information about the resource path, including the path string, and the parameters required to resolve the resource path, and the resolver function used to fetch and validate a single resource instance or a collection of resource instances.
ResourcePath
ResourcePath(root: ResourceType, *path: str)
Bases: Iterable[ResourceNode['BaseResource']]
A resource path within the resources graph.
The resource path represents a sequence of linked fields within the resources graph. It is used to navigate the resources graph and build API paths to interact with the resources.
Attributes:
Name | Type | Description |
---|---|---|
nodes |
A list of |
Initialize a new resource path.
It initializes a new resource path with the provided root resource and path segments. The path segments represent a sequence of linked fields within the resources graph, and together with the root resource they define a resource path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
root
|
ResourceType
|
The root resource of the API path serving as the starting point in the resources graph. |
required |
*path
|
str
|
Variable length argument list representing the path segments of the resource path. Each segment corresponds to a linked field alias within the resources graph. |
()
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
goto
Navigate to the provided path segments.
It navigates to the provided path segments within the resources graph. Each segment is checked to match a linked field alias within the resource hierarchy. If any segment fails to match a field alias in the resource hierarchy, an error is raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*path
|
str
|
Variable length argument list representing the path segments to navigate within the resources graph. Each segment corresponds to a linked field alias within the resources graph. |
()
|
in_place
|
bool
|
A flag indicating whether to navigate in place or create
a new resource path. Defaults to |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If any of the provided segments do not correspond to a linked field alias in the resource hierarchy. |
Note
A provided path arg can be a dot-separated string representing
multiple segments. For example, the path arg foo.bar
is split
into two segments foo
and bar
.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 |
|
walk
walk(
_guard: frozenset[str] = frozenset(),
/,
max_depth: int = 2,
skip_root: bool = False,
) -> Generator[Self, None, None]
Walk the resource graph and yield all possible sub-paths.
It recursively walks the resource graph and yields all possible sub-paths up to the specified maximum depth. The maximum depth is used to limit the recursion depth and avoid infinite loops when walking the resource graph. Already walked paths are skipped to avoid duplicates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
_guard
|
frozenset[str]
|
A set of already walked resource association alias. It should not be used directly and is only meant to be used internally for recursion. |
frozenset()
|
max_depth
|
int
|
The maximum depth to walk the resource graph. It limits
the recursion depth and avoids infinite loops.
Defaults to |
2
|
skip_root
|
bool
|
A flag indicating whether to skip the root resource
path. Defaults to |
False
|
Yields:
Type | Description |
---|---|
Self
|
All possible sub-paths up to the specified maximum depth. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
ResourceManager
Bases: Manager[Resource]
A resource class manager.
It provides a common interface to access and manage the service methods associated with a resource class.
Initialize the resource manager.
It initializes the resource manager with the provided resource class, and collects all resource public instance methods decorated with the route decorator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[Resource]
|
The resource class to manage. |
required |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
exists
async
exists(
__session: AsyncSession | None = None, /, **kwargs: Any
) -> bool
Check if a resource instance exist based on the given filters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__session
|
AsyncSession | None
|
The async session to use for the operation. If not
provided, the session in the current context is used.
Defaults to |
None
|
**kwargs
|
Any
|
The filters to apply when querying the resource instances as keyword arguments with the field aliases as keys and the values to filter by as values. |
{}
|
Returns:
Type | Description |
---|---|
bool
|
|
bool
|
filters, otherwise |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
get
async
get(
__session: AsyncSession | None = None, /, **kwargs: Any
) -> Resource | None
Get a single resource instance based on the given filters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__session
|
AsyncSession | None
|
The async session to use for the operation. If not
provided, the session in the current context is used.
Defaults to |
None
|
**kwargs
|
Any
|
The filters to apply when querying the resource instances as keyword arguments with the field aliases as keys and the values to filter by as values. |
{}
|
Returns:
Type | Description |
---|---|
Resource | None
|
A single resource instance that matches the provided filters, or |
Resource | None
|
|
Note
This method is equivalent to the get_one
method, but it returns
None
if no resource instance is found for the provided filters
instead of raising an exception.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
get_many
async
get_many(
__session: AsyncSession | None = None, /, **kwargs: Any
) -> Sequence[Resource]
Get a collection of resource instances based on the given filters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__session
|
AsyncSession | None
|
The async session to use for the operation. If not
provided, the session in the current context is used.
Defaults to |
None
|
**kwargs
|
Any
|
The filters to apply when querying the resource instances as keyword arguments with the field aliases as keys and the values to filter by as values. |
{}
|
Returns:
Type | Description |
---|---|
Sequence[Resource]
|
A collection of resource instances that match the provided filters. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
get_one
async
get_one(
__session: AsyncSession | None = None, /, **kwargs: Any
) -> Resource
Get exactly one resource instance based on the given filters.
It returns exactly one resource instance that matches the provided filters, or raises an exception if no resource instance is found.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__session
|
AsyncSession | None
|
The async session to use for the operation. If not
provided, the session in the current context is used.
Defaults to |
None
|
**kwargs
|
Any
|
The filters to apply when querying the resource instances as keyword arguments with the field aliases as keys and the values to filter by as values. |
{}
|
Raises:
Type | Description |
---|---|
ValueError
|
If no resource instance is found. |
Returns:
Type | Description |
---|---|
Resource
|
A single resource instance that matches the provided filters. |
Note
This method is equivalent to the get
method, but it raises an
exception if no resource instance is found for the provided filters
instead of returning None
.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
ResourceState
A resource class state.
It provides utilities to manage the state of a resource class, including its lifecycle status and scheduled tasks associated with the resource class build.
Initialize the resource state.
It initializes the resource state with the provided resource class and
sets the lifecycle status to RESOLVED
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[Resource]
|
The resource class owner of the state. |
required |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
flush
flush(
_check_guard: set[str] | None = None,
_flush_guard: set[str] | None = None,
*,
until: SchedulableState | None = None,
) -> bool | None
Advance the resource through its lifecycle states.
This method handles the transition through lifecycle states while managing dependencies and preventing circular references. For each state transition, it ensures all dependencies have reached the required state, executes any scheduled tasks, and propagates the state change to dependent resources.
The flush operation follows these steps: 1. Check and handle any base resources (inheritance-based dependencies) 2. Verify all resource dependencies have reached the required state 3. Execute scheduled tasks for the next state 4. Update the resource state 5. Propagate state changes to dependent resources
Parameters:
Name | Type | Description | Default |
---|---|---|---|
_check_guard
|
set[str] | None
|
Internal set to prevent circular dependency checks. Used to track which resources have been processed during dependency validation. Defaults to an empty set. |
None
|
_flush_guard
|
set[str] | None
|
Internal set to prevent recursive flush operations. Used to detect and break circular flush attempts between interdependent resources. Defaults to an empty set. |
None
|
until
|
SchedulableState | None
|
The target lifecycle state to reach. The flush operation
will advance the resource state up to this point but not
beyond. If not specified, attempts to reach the |
None
|
Returns:
Type | Description |
---|---|
bool | None
|
|
bool | None
|
state change is needed (already at target state or detected |
bool | None
|
recursion), or recursively continues flushing until target state is |
bool | None
|
reached. Otherwise, returns |
bool | None
|
advancement. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 |
|
schedule
schedule(
*tasks: Task,
_guard: set[str] | None = None,
when: SchedulableState | None = None,
when_reached: Literal[
"fallback", "run", "skip"
] = "run",
when_future: Literal["await", "skip"] = "await",
propagate: bool = False,
) -> None
Schedule tasks for execution.
It schedules tasks for immediate or future execution based on resource
lifecycle states. Each task can target a specific state, with
configurable behavior for handling already reached states using the
when_reached
option, and future states using the when_future
option. Both strategies can be used concurrently to handle different
scenarios. Tasks scheduled for the same lifecycle state execute
sequentially in the order they were added.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*tasks
|
Task
|
The tasks to execute or schedule for the resource state. Multiple tasks scheduled for the same state are executed sequentially in the order they were added. |
()
|
_guard
|
set[str] | None
|
Internal set to prevent recursive schedule propagation operations. Used to detect and break circular schedule attempts between interdependent resources. Defaults to an empty set. |
None
|
when
|
SchedulableState | None
|
Default scheduling state for the provided tasks. If a task
doesn't specify its own lifecycle state to schedule for, this
value is used. When |
None
|
when_reached
|
Literal['fallback', 'run', 'skip']
|
The strategy to apply when a task is scheduled for a
state that has already been reached. It can be set to one of
the following values:
- |
'run'
|
when_future
|
Literal['await', 'skip']
|
The strategy to apply when a task is scheduled for a
future state. It can be set to one of the following values:
- |
'await'
|
propagate
|
bool
|
Whether to propagate and apply the same scheduled tasks
to all dependent and child resources. Defaults to |
False
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 |
|
ResourceMeta
Bases: ABCMeta
, ConfigurableMeta
, DeclarativeMeta
Meta class for the base resource class.
Initialize the resource meta class.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
objects
property
objects: ResourceManager[BaseResource]
The resource manager that provides service methods on objects.
collect_config_wrappers
Collect configuration wrappers from the given bases and namespace.
It collects the configuration wrappers from the given bases and namespace by extracting the configuration wrapper type from the original bases annotation if it is a generic subclass of the configurable class or metaclass, and from the configuration attribute if present in the class and bases namespace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bases
|
tuple[type, ...]
|
The class bases. |
required |
namespace
|
dict[str, Any]
|
The class namespace. |
required |
Returns:
Type | Description |
---|---|
list[ConfigType]
|
A list of configuration wrapper classes found in the given bases |
list[ConfigType]
|
and namespace. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/config.py
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 |
|
BaseResource
BaseResource(
__model: BaseModel | None = None,
__context: dict[str, Any] | None = None,
/,
**data: Any,
)
Bases: Representation
, Configurable[ResourceConfig]
Base class for all resources.
It exposes the base class for all resources within the Plateforme framework. A resource owns a data model and provides a set of services to interact with.
FIXME: Fix MyPy stub schema models typing. FIXME: Fix MyPy SQLAlchemy instrumented attributes typing.
Attributes:
Name | Type | Description |
---|---|---|
__config__ |
ResourceConfig | ConfigDict[ResourceConfigDict]
|
The configuration class setter for the resource. |
__config_services__ |
tuple[BaseService, ...]
|
The services configured for the resource. |
__config_specs__ |
tuple[SpecType, ...]
|
The specifications applied to the resource. |
__manager__ |
tuple[SpecType, ...]
|
The resource manager used to access and manage the service methods associated with the resource class. |
__state__ |
tuple[SpecType, ...]
|
The resource state used to manage the resource lifecycle operations, such as creating, initializing, and building the resource class and its dependencies. Additionally, it is used to manage the tasks needed to complete the resource class building process. |
__tablename__ |
str | None
|
The name of the table in the database. |
__table_args__ |
Any
|
The arguments for the table in the database. |
__mapper_args__ |
Any
|
The arguments for the mapper in the database. |
_sa_class_manager |
ClassManager[Self]
|
The SQLAlchemy class manager of the resource. |
_sa_instance_state |
InstanceState[Self]
|
The SQLAlchemy instance state of the resource used for ORM operations. |
_sa_registry |
Registry
|
The SQLAlchemy registry of the resource. It is handled dynamically by the Plateforme application. |
__class_vars__ |
Registry
|
The names of classvars defined on the model. |
__private_attributes__ |
Registry
|
Metadata about the private attributes of the model. |
__signature__ |
Registry
|
The signature for instantiating the model. |
__pydantic_complete__ |
bool
|
Whether resource model building is completed, or if there are still undefined fields. |
__pydantic_validated__ |
bool
|
Whether the resource model has been validated or directly constructed. |
__pydantic_core_schema__ |
bool
|
The pydantic-core schema used to build the
|
__pydantic_model_schema__ |
CoreSchema
|
The pydantic-core schema used to build the underlying resource model. |
__pydantic_custom_init__ |
CoreSchema
|
Whether the resource model has a custom
|
__pydantic_decorators__ |
CoreSchema
|
Metadata containing the decorators defined on the resource model. |
__pydantic_generic_metadata__ |
CoreSchema
|
Metadata for generic resource models, it
contains data used for a similar purpose to |
__pydantic_parent_namespace__ |
CoreSchema
|
Parent namespace of the resource model, used for automatic rebuilding of resource models. |
__pydantic_post_init__ |
None | Literal['resource_post_init']
|
The name of the post-init method for the resource model, if defined. |
__pydantic_root_model__ |
None | Literal['resource_post_init']
|
Whether the resource model is an
implementation of the |
__pydantic_adapter__ |
TypeAdapterList[BaseResource]
|
The pydantic |
__pydantic_serializer__ |
TypeAdapterList[BaseResource]
|
The pydantic-core |
__pydantic_validator__ |
TypeAdapterList[BaseResource]
|
The pydantic-core |
__pydantic_extra__ |
TypeAdapterList[BaseResource]
|
An instance attribute with the values of extra
fields from validation when |
__pydantic_fields_set__ |
TypeAdapterList[BaseResource]
|
An instance attribute with the names of fields explicitly set. |
__pydantic_private__ |
TypeAdapterList[BaseResource]
|
Instance attribute with the values of private attributes set on the resource model instance. |
Initialize a resource instance.
It initializes a resource instance by parsing and validating input data
from the data
keyword arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__model
|
BaseModel | None
|
The model instance to use to create the resource instance.
This lets the resource instance be created with an existing
model instance within the |
None
|
__context
|
dict[str, Any] | None
|
The context dictionary to use to initialize the resource instance. It is passed to the post-init method. |
None
|
**data
|
Any
|
The input data to initialize the resource instance if no
model instance is provided. Note that |
{}
|
Note
The mangled arguments are injected by SQLAlchemy internal behavior within the keyword arguments. Hence, they need to be parsed and removed from the data dictionary before initializing the resource instance.
The validation can be strictly enforced or skipped using the
validation context manager validation_manager
defined in the
schema core module. This can be necessary to allow the resource to
be initialized with an already validated model instance and avoid
triggering the Pydantic validation logic.
When a resource is created directly by SQLAlchemy, while querying
the database for instance, the __init__
method is not called and
the data is set directly on the model instance without validation.
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource instance could not be initialized
from the provided input data. For instance, if the input data
is invalid and raises a |
AttributeError
|
If an attribute is not an instrumented attribute of the resource instance while it is defined as a model field. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 |
|
resource_extra
property
resource_fields_set
property
resource_adapter
resource_adapter() -> TypeAdapterList[BaseResource]
Get the resource type adapter.
Returns:
Type | Description |
---|---|
TypeAdapterList[BaseResource]
|
The resource type adapter used to validate and serialize instances |
TypeAdapterList[BaseResource]
|
of the resource model. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_computed_fields
resource_computed_fields() -> dict[str, ComputedFieldInfo]
Get computed fields defined on this resource class.
Returns:
Type | Description |
---|---|
dict[str, ComputedFieldInfo]
|
A metadata dictionary of computed field names and their |
dict[str, ComputedFieldInfo]
|
corresponding |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_fields
resource_fields() -> dict[str, ResourceFieldInfo]
Get fields defined on this resource class.
Returns:
Type | Description |
---|---|
dict[str, ResourceFieldInfo]
|
A metadata dictionary of field names and their corresponding |
dict[str, ResourceFieldInfo]
|
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_path
resource_path() -> str
resource_add
async
resource_add(
*, session: AsyncSession | None = None
) -> None
Add the resource instance to the database.
It places an object into the current AsyncSession
.
Objects that are in the transient
state when passed to the
session.add
method will move to the pending
state, until the next
flush, at which point they will move to the persistent
state.
Objects that are in the detached
state when passed to the
session.add
method will move to the persistent
state directly.
If the transaction used by the AsyncSession
is rolled back, objects
which were transient when they were passed to session.add
will be
moved back to the transient
state, and will no longer be present
within this AsyncSession
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session
|
AsyncSession | None
|
The session to use for the operation. If not provided, the
session in the current context is used.
Defaults to |
None
|
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource instance could not be added to the database. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_construct
classmethod
resource_construct(
_fields_set: set[str] | None = None,
_model: BaseModel | None = None,
**data: Any,
) -> Resource
Creates a new instance of the resource class with validated data.
Creates a new resource setting underlying model __dict__
and
__pydantic_fields_set__
from trusted or pre-validated data. Default
values are respected, but no other validation is performed. It behaves
as if resource_config.extra = 'allow'
was set since it adds all
passed values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
_fields_set
|
set[str] | None
|
The set of field names accepted by the resource instance. |
None
|
_model
|
BaseModel | None
|
The model instance to use to create the resource instance. If not provided, a new model instance is created. |
None
|
**data
|
Any
|
Trusted or pre-validated input data to initialize the
resource. It is used to set the |
{}
|
Returns:
Type | Description |
---|---|
Resource
|
A new instance of the resource class with validated data. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_copy
Returns a copy of the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
update
|
dict[str, Any] | None
|
Values to add/modify within the resource. Note that if
assignment validation is not set to |
None
|
deep
|
bool
|
Set to |
False
|
Returns:
Type | Description |
---|---|
Resource
|
A new copy of the model instance with the updated values. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_delete
async
resource_delete(
*, session: AsyncSession | None = None
) -> None
Delete the resource instance from the database.
It marks an instance as deleted.
The object is assumed to be either persistent
or detached
when
passed; after the method is called, the object will remain in the
persistent
state until the next flush proceeds. During this time,
the object will also be a member of the session.deleted
collection.
When the next flush proceeds, the object will move to the deleted
state, indicating a DELETE
statement was emitted for its row within
the current transaction. When the transaction is successfully
committed, the deleted object is moved to the detached
state and is
no longer present within this AsyncSession
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session
|
AsyncSession | None
|
The session to use for the operation. If not provided, the
session in the current context is used.
Defaults to |
None
|
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource instance could not be deleted from the database. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_dump
resource_dump(
*,
mode: Literal["json", "python", "raw"] | str = "python",
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> dict[str, Any]
Generate a dictionary representation of the resource.
It is used to dump the resource instance to a dictionary representation of the resource, optionally specifying which fields to include or exclude.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode
|
Literal['json', 'python', 'raw'] | str
|
The mode in which |
'python'
|
include
|
IncEx | None
|
A list of fields to include in the output.
Defaults to |
None
|
exclude
|
IncEx | None
|
A list of fields to exclude from the output.
Defaults to |
None
|
by_alias
|
bool
|
Whether to use the field's alias in the dictionary key if
defined. Defaults to |
False
|
exclude_unset
|
bool
|
Whether to exclude fields that have not been
explicitly set. Defaults to |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields that are set to their
default value. Defaults to |
False
|
exclude_none
|
bool
|
Whether to exclude fields that have a value of
|
False
|
round_trip
|
bool
|
If |
False
|
warnings
|
bool
|
Whether to log warnings when invalid fields are
encountered. Defaults to |
True
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A dictionary representation of the resource. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_dump_json
resource_dump_json(
*,
indent: int | None = None,
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> str
Generate a JSON representation of the resource.
It is used to dump the resource instance to a JSON representation of
the resource using Pydantic's to_json
method, optionally specifying
which fields to include or exclude.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
indent
|
int | None
|
Indentation to use in the JSON output. If |
None
|
include
|
IncEx | None
|
A list of fields to include in the JSON output.
Defaults to |
None
|
exclude
|
IncEx | None
|
A list of fields to exclude from the JSON output.
Defaults to |
None
|
by_alias
|
bool
|
Whether to use the field's alias in the dictionary key if
defined. Defaults to |
False
|
exclude_unset
|
bool
|
Whether to exclude fields that have not been
explicitly set. Defaults to |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields that are set to their
default value. Defaults to |
False
|
exclude_none
|
bool
|
Whether to exclude fields that have a value of
|
False
|
round_trip
|
bool
|
If |
False
|
warnings
|
bool
|
Whether to log warnings when invalid fields are
encountered. Defaults to |
True
|
Returns:
Type | Description |
---|---|
str
|
A JSON string representation of the resource. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_json_schema
classmethod
resource_json_schema(
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[
GenerateJsonSchema
] = GenerateJsonSchema,
mode: JsonSchemaMode = "validation",
source: JsonSchemaSource = "key",
) -> dict[str, Any]
Generates a JSON schema for a resource class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by_alias
|
bool
|
Whether to use field aliases when generating the schema,
i.e. if |
True
|
ref_template
|
str
|
The template format string used when generating
reference names. Defaults to |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
The class to use for generating the JSON Schema. |
GenerateJsonSchema
|
mode
|
JsonSchemaMode
|
The mode to use for generating the JSON Schema. It can be
either |
'validation'
|
source
|
JsonSchemaSource
|
The source type to use for generating the resources JSON
schema. It can be either |
'key'
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The generated JSON schema of the resource class. |
Note
The schema generator class can be overridden to customize the
logic used to generate the JSON schema. This can be done by
subclassing the GenerateJsonSchema
class and passing the subclass
as the schema_generator
argument.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_keychain
Collect all keys set on the resource instance.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_merge
async
resource_merge(
*,
load: bool = True,
options: Sequence[ORMOption] | None = None,
session: AsyncSession | None = None,
) -> Resource
Merge the resource instance with the database.
It copies the state of the resource instance into a corresponding
instance in the database within the current AsyncSession
.
First, it examines the primary key attributes if available, otherwise
the resource identifier keychain, and attempts to reconcile it with an
instance of the same identifier in the session. If not found locally,
it attempts to load the object from the database based on the
identifier, and if none can be located, creates a new instance in the
session. The state of each attribute on the source instance is then
copied to the target instance. The resulting target instance is then
returned by the resource_merge
method; the original source instance
is left unmodified, and un-associated with the AsyncSession
if not
already.
This operation cascades to associated instances if the association is
mapped with cascade='merge'
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
load
|
bool
|
Whether to load the resource instance from the database if
not found in the session. Defaults to When The |
True
|
options
|
Sequence[ORMOption] | None
|
Optional sequence of loader options which will be applied
to the |
None
|
session
|
AsyncSession | None
|
The session to use for the operation. If not provided, the
session in the current context is used.
Defaults to |
None
|
Returns:
Type | Description |
---|---|
Resource
|
The merged resource instance. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 |
|
resource_parametrized_name
classmethod
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic Base resopurces.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
tuple[type[Any], ...]
|
Tuple of types of the class. Given a generic class
|
required |
Returns:
Type | Description |
---|---|
str
|
String representing the new class where |
str
|
|
Raises:
Type | Description |
---|---|
TypeError
|
Raised when trying to generate concrete names for non-generic resources. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_post_init
Post-initialization method for the resource class.
Override this method to perform additional initialization after the
__init__
and resource_construct
methods have been called. This is
useful in scenarios where it is necessary to perform additional
initialization steps after the resource has been fully initialized.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__context
|
dict[str, Any] | None
|
The context object passed to the resource instance. |
None
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_rebuild
classmethod
resource_rebuild(
*,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: dict[str, Any] | None = None,
) -> bool | None
Rebuild the pydantic-core schema for the resource.
This may be necessary when one of the annotations is a ForwardRef
which could not be resolved during the initial attempt to build the
schema, and automatic rebuilding fails.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
force
|
bool
|
Whether to force the rebuilding of the resource schema.
Defaults to |
False
|
raise_errors
|
bool
|
Whether to raise errors or fail silently.
Defaults to |
True
|
_parent_namespace_depth
|
int
|
The depth level of the parent namespace. Defaults to 2. |
2
|
_types_namespace
|
dict[str, Any] | None
|
The types namespace. Defaults to |
None
|
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource adapter or schema could not be
rebuilt and |
PydanticUndefinedAnnotation
|
If |
Returns:
Type | Description |
---|---|
bool | None
|
Returns |
bool | None
|
was not required. If rebuilding was required, returns |
bool | None
|
rebuilding was successful, otherwise |
bool | None
|
occurred and |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_revalidate
resource_revalidate(
*,
force: bool = False,
raise_errors: bool = True,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> bool | None
Revalidate the resource instance.
It revalidates the resource instance in place, enforcing the types
strictly if specified. If the resource instance has already been
validated, it will not be revalidated unless the force
argument is
set to True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
force
|
bool
|
Whether to force the revalidation of the resource instance.
Defaults to |
False
|
raise_errors
|
bool
|
Whether to raise errors or fail silently.
Defaults to |
True
|
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If the resource instance could not be validated
and |
Returns:
Type | Description |
---|---|
bool | None
|
Returns |
bool | None
|
and revalidation was not required. If validation was required, |
bool | None
|
returns |
bool | None
|
if an error occurred and |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_update
resource_update(
obj: Any,
*,
update: dict[str, Any] | None = None,
from_attributes: bool | None = None,
) -> None
Update the resource with the given object and update dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to update the resource with. It can be a dictionary
or an object with attributes (if |
required |
update
|
dict[str, Any] | None
|
Values to add/modify within the resource. Note that if
assignment validation is not set to |
None
|
from_attributes
|
bool | None
|
Whether to extract data from object attributes.
Defaults to |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If the object could not be validated. |
ValueError
|
If |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate
classmethod
resource_validate(
obj: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> Resource
Validate the given object against the resource.
It validates the provided object against the resource model and returns
the validated resource instance. The validation can be strictly
enforced or skipped using the strict
argument. The data can be
extracted from the object attributes using the from_attributes
argument. Additional context can be passed to the validator using the
context
argument.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
from_attributes
|
bool | None
|
Whether to extract data from the object attributes. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Resource
|
A validated resource instance. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_many
classmethod
resource_validate_many(
obj: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> Sequence[Resource]
Validate the given object collection against the resource.
It validates the provided object collection against the resource model
and returns the validated resource instances. The validation can be
strictly enforced or skipped using the strict
argument. The data can
be extracted from the object items attributes using the
from_attributes
argument. Additional context can be passed to the
validator using the context
argument.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object collection to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
from_attributes
|
bool | None
|
Whether to extract data from the object collection items attributes. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Sequence[Resource]
|
A validated collection of resource instances. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object collection could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_json
classmethod
resource_validate_json(
json_data: str | bytes | bytearray,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Resource
Validate the given JSON data against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_data
|
str | bytes | bytearray
|
The JSON data to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Resource
|
A validated resource instance. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValidationError
|
If the object could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_json_many
classmethod
resource_validate_json_many(
json_data: str | bytes | bytearray,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Sequence[Resource]
Validate the given JSON data collection against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_data
|
str | bytes | bytearray
|
The JSON data collection to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Sequence[Resource]
|
A validated collection of resource instances. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValidationError
|
If the object collection could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_strings
classmethod
resource_validate_strings(
obj: Any,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Resource
Validate the given string object against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The string object to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Resource
|
A validated resource instance. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_strings_many
classmethod
resource_validate_strings_many(
obj: Any,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Sequence[Resource]
Validate the given string object collection against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The string object collection to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Sequence[Resource]
|
A validated collection of resource instances. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object collection could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
CRUDResource
CRUDResource(
__model: BaseModel | None = None,
__context: dict[str, Any] | None = None,
/,
**data: Any,
)
Bases: BaseResource
A CRUD resource.
It inherits directly from the BaseResource
and adds the CRUDService
to its configuration services. This enables all CRUD operations on the
resource instances.
Initialize a resource instance.
It initializes a resource instance by parsing and validating input data
from the data
keyword arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__model
|
BaseModel | None
|
The model instance to use to create the resource instance.
This lets the resource instance be created with an existing
model instance within the |
None
|
__context
|
dict[str, Any] | None
|
The context dictionary to use to initialize the resource instance. It is passed to the post-init method. |
None
|
**data
|
Any
|
The input data to initialize the resource instance if no
model instance is provided. Note that |
{}
|
Note
The mangled arguments are injected by SQLAlchemy internal behavior within the keyword arguments. Hence, they need to be parsed and removed from the data dictionary before initializing the resource instance.
The validation can be strictly enforced or skipped using the
validation context manager validation_manager
defined in the
schema core module. This can be necessary to allow the resource to
be initialized with an already validated model instance and avoid
triggering the Pydantic validation logic.
When a resource is created directly by SQLAlchemy, while querying
the database for instance, the __init__
method is not called and
the data is set directly on the model instance without validation.
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource instance could not be initialized
from the provided input data. For instance, if the input data
is invalid and raises a |
AttributeError
|
If an attribute is not an instrumented attribute of the resource instance while it is defined as a model field. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 |
|
resource_extra
property
resource_fields_set
property
resource_adapter
resource_adapter() -> TypeAdapterList[BaseResource]
Get the resource type adapter.
Returns:
Type | Description |
---|---|
TypeAdapterList[BaseResource]
|
The resource type adapter used to validate and serialize instances |
TypeAdapterList[BaseResource]
|
of the resource model. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_computed_fields
resource_computed_fields() -> dict[str, ComputedFieldInfo]
Get computed fields defined on this resource class.
Returns:
Type | Description |
---|---|
dict[str, ComputedFieldInfo]
|
A metadata dictionary of computed field names and their |
dict[str, ComputedFieldInfo]
|
corresponding |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_fields
resource_fields() -> dict[str, ResourceFieldInfo]
Get fields defined on this resource class.
Returns:
Type | Description |
---|---|
dict[str, ResourceFieldInfo]
|
A metadata dictionary of field names and their corresponding |
dict[str, ResourceFieldInfo]
|
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_path
resource_path() -> str
resource_add
async
resource_add(
*, session: AsyncSession | None = None
) -> None
Add the resource instance to the database.
It places an object into the current AsyncSession
.
Objects that are in the transient
state when passed to the
session.add
method will move to the pending
state, until the next
flush, at which point they will move to the persistent
state.
Objects that are in the detached
state when passed to the
session.add
method will move to the persistent
state directly.
If the transaction used by the AsyncSession
is rolled back, objects
which were transient when they were passed to session.add
will be
moved back to the transient
state, and will no longer be present
within this AsyncSession
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session
|
AsyncSession | None
|
The session to use for the operation. If not provided, the
session in the current context is used.
Defaults to |
None
|
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource instance could not be added to the database. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_construct
classmethod
resource_construct(
_fields_set: set[str] | None = None,
_model: BaseModel | None = None,
**data: Any,
) -> Resource
Creates a new instance of the resource class with validated data.
Creates a new resource setting underlying model __dict__
and
__pydantic_fields_set__
from trusted or pre-validated data. Default
values are respected, but no other validation is performed. It behaves
as if resource_config.extra = 'allow'
was set since it adds all
passed values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
_fields_set
|
set[str] | None
|
The set of field names accepted by the resource instance. |
None
|
_model
|
BaseModel | None
|
The model instance to use to create the resource instance. If not provided, a new model instance is created. |
None
|
**data
|
Any
|
Trusted or pre-validated input data to initialize the
resource. It is used to set the |
{}
|
Returns:
Type | Description |
---|---|
Resource
|
A new instance of the resource class with validated data. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_copy
Returns a copy of the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
update
|
dict[str, Any] | None
|
Values to add/modify within the resource. Note that if
assignment validation is not set to |
None
|
deep
|
bool
|
Set to |
False
|
Returns:
Type | Description |
---|---|
Resource
|
A new copy of the model instance with the updated values. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_delete
async
resource_delete(
*, session: AsyncSession | None = None
) -> None
Delete the resource instance from the database.
It marks an instance as deleted.
The object is assumed to be either persistent
or detached
when
passed; after the method is called, the object will remain in the
persistent
state until the next flush proceeds. During this time,
the object will also be a member of the session.deleted
collection.
When the next flush proceeds, the object will move to the deleted
state, indicating a DELETE
statement was emitted for its row within
the current transaction. When the transaction is successfully
committed, the deleted object is moved to the detached
state and is
no longer present within this AsyncSession
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session
|
AsyncSession | None
|
The session to use for the operation. If not provided, the
session in the current context is used.
Defaults to |
None
|
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource instance could not be deleted from the database. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_dump
resource_dump(
*,
mode: Literal["json", "python", "raw"] | str = "python",
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> dict[str, Any]
Generate a dictionary representation of the resource.
It is used to dump the resource instance to a dictionary representation of the resource, optionally specifying which fields to include or exclude.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode
|
Literal['json', 'python', 'raw'] | str
|
The mode in which |
'python'
|
include
|
IncEx | None
|
A list of fields to include in the output.
Defaults to |
None
|
exclude
|
IncEx | None
|
A list of fields to exclude from the output.
Defaults to |
None
|
by_alias
|
bool
|
Whether to use the field's alias in the dictionary key if
defined. Defaults to |
False
|
exclude_unset
|
bool
|
Whether to exclude fields that have not been
explicitly set. Defaults to |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields that are set to their
default value. Defaults to |
False
|
exclude_none
|
bool
|
Whether to exclude fields that have a value of
|
False
|
round_trip
|
bool
|
If |
False
|
warnings
|
bool
|
Whether to log warnings when invalid fields are
encountered. Defaults to |
True
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A dictionary representation of the resource. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_dump_json
resource_dump_json(
*,
indent: int | None = None,
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True,
) -> str
Generate a JSON representation of the resource.
It is used to dump the resource instance to a JSON representation of
the resource using Pydantic's to_json
method, optionally specifying
which fields to include or exclude.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
indent
|
int | None
|
Indentation to use in the JSON output. If |
None
|
include
|
IncEx | None
|
A list of fields to include in the JSON output.
Defaults to |
None
|
exclude
|
IncEx | None
|
A list of fields to exclude from the JSON output.
Defaults to |
None
|
by_alias
|
bool
|
Whether to use the field's alias in the dictionary key if
defined. Defaults to |
False
|
exclude_unset
|
bool
|
Whether to exclude fields that have not been
explicitly set. Defaults to |
False
|
exclude_defaults
|
bool
|
Whether to exclude fields that are set to their
default value. Defaults to |
False
|
exclude_none
|
bool
|
Whether to exclude fields that have a value of
|
False
|
round_trip
|
bool
|
If |
False
|
warnings
|
bool
|
Whether to log warnings when invalid fields are
encountered. Defaults to |
True
|
Returns:
Type | Description |
---|---|
str
|
A JSON string representation of the resource. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_json_schema
classmethod
resource_json_schema(
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[
GenerateJsonSchema
] = GenerateJsonSchema,
mode: JsonSchemaMode = "validation",
source: JsonSchemaSource = "key",
) -> dict[str, Any]
Generates a JSON schema for a resource class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by_alias
|
bool
|
Whether to use field aliases when generating the schema,
i.e. if |
True
|
ref_template
|
str
|
The template format string used when generating
reference names. Defaults to |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
The class to use for generating the JSON Schema. |
GenerateJsonSchema
|
mode
|
JsonSchemaMode
|
The mode to use for generating the JSON Schema. It can be
either |
'validation'
|
source
|
JsonSchemaSource
|
The source type to use for generating the resources JSON
schema. It can be either |
'key'
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The generated JSON schema of the resource class. |
Note
The schema generator class can be overridden to customize the
logic used to generate the JSON schema. This can be done by
subclassing the GenerateJsonSchema
class and passing the subclass
as the schema_generator
argument.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_keychain
Collect all keys set on the resource instance.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_merge
async
resource_merge(
*,
load: bool = True,
options: Sequence[ORMOption] | None = None,
session: AsyncSession | None = None,
) -> Resource
Merge the resource instance with the database.
It copies the state of the resource instance into a corresponding
instance in the database within the current AsyncSession
.
First, it examines the primary key attributes if available, otherwise
the resource identifier keychain, and attempts to reconcile it with an
instance of the same identifier in the session. If not found locally,
it attempts to load the object from the database based on the
identifier, and if none can be located, creates a new instance in the
session. The state of each attribute on the source instance is then
copied to the target instance. The resulting target instance is then
returned by the resource_merge
method; the original source instance
is left unmodified, and un-associated with the AsyncSession
if not
already.
This operation cascades to associated instances if the association is
mapped with cascade='merge'
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
load
|
bool
|
Whether to load the resource instance from the database if
not found in the session. Defaults to When The |
True
|
options
|
Sequence[ORMOption] | None
|
Optional sequence of loader options which will be applied
to the |
None
|
session
|
AsyncSession | None
|
The session to use for the operation. If not provided, the
session in the current context is used.
Defaults to |
None
|
Returns:
Type | Description |
---|---|
Resource
|
The merged resource instance. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 |
|
resource_parametrized_name
classmethod
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic Base resopurces.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
tuple[type[Any], ...]
|
Tuple of types of the class. Given a generic class
|
required |
Returns:
Type | Description |
---|---|
str
|
String representing the new class where |
str
|
|
Raises:
Type | Description |
---|---|
TypeError
|
Raised when trying to generate concrete names for non-generic resources. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_post_init
Post-initialization method for the resource class.
Override this method to perform additional initialization after the
__init__
and resource_construct
methods have been called. This is
useful in scenarios where it is necessary to perform additional
initialization steps after the resource has been fully initialized.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__context
|
dict[str, Any] | None
|
The context object passed to the resource instance. |
None
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_rebuild
classmethod
resource_rebuild(
*,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: dict[str, Any] | None = None,
) -> bool | None
Rebuild the pydantic-core schema for the resource.
This may be necessary when one of the annotations is a ForwardRef
which could not be resolved during the initial attempt to build the
schema, and automatic rebuilding fails.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
force
|
bool
|
Whether to force the rebuilding of the resource schema.
Defaults to |
False
|
raise_errors
|
bool
|
Whether to raise errors or fail silently.
Defaults to |
True
|
_parent_namespace_depth
|
int
|
The depth level of the parent namespace. Defaults to 2. |
2
|
_types_namespace
|
dict[str, Any] | None
|
The types namespace. Defaults to |
None
|
Raises:
Type | Description |
---|---|
PlateformeError
|
If the resource adapter or schema could not be
rebuilt and |
PydanticUndefinedAnnotation
|
If |
Returns:
Type | Description |
---|---|
bool | None
|
Returns |
bool | None
|
was not required. If rebuilding was required, returns |
bool | None
|
rebuilding was successful, otherwise |
bool | None
|
occurred and |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_revalidate
resource_revalidate(
*,
force: bool = False,
raise_errors: bool = True,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> bool | None
Revalidate the resource instance.
It revalidates the resource instance in place, enforcing the types
strictly if specified. If the resource instance has already been
validated, it will not be revalidated unless the force
argument is
set to True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
force
|
bool
|
Whether to force the revalidation of the resource instance.
Defaults to |
False
|
raise_errors
|
bool
|
Whether to raise errors or fail silently.
Defaults to |
True
|
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If the resource instance could not be validated
and |
Returns:
Type | Description |
---|---|
bool | None
|
Returns |
bool | None
|
and revalidation was not required. If validation was required, |
bool | None
|
returns |
bool | None
|
if an error occurred and |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_update
resource_update(
obj: Any,
*,
update: dict[str, Any] | None = None,
from_attributes: bool | None = None,
) -> None
Update the resource with the given object and update dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to update the resource with. It can be a dictionary
or an object with attributes (if |
required |
update
|
dict[str, Any] | None
|
Values to add/modify within the resource. Note that if
assignment validation is not set to |
None
|
from_attributes
|
bool | None
|
Whether to extract data from object attributes.
Defaults to |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If the object could not be validated. |
ValueError
|
If |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate
classmethod
resource_validate(
obj: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> Resource
Validate the given object against the resource.
It validates the provided object against the resource model and returns
the validated resource instance. The validation can be strictly
enforced or skipped using the strict
argument. The data can be
extracted from the object attributes using the from_attributes
argument. Additional context can be passed to the validator using the
context
argument.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
from_attributes
|
bool | None
|
Whether to extract data from the object attributes. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Resource
|
A validated resource instance. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_many
classmethod
resource_validate_many(
obj: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> Sequence[Resource]
Validate the given object collection against the resource.
It validates the provided object collection against the resource model
and returns the validated resource instances. The validation can be
strictly enforced or skipped using the strict
argument. The data can
be extracted from the object items attributes using the
from_attributes
argument. Additional context can be passed to the
validator using the context
argument.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object collection to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
from_attributes
|
bool | None
|
Whether to extract data from the object collection items attributes. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Sequence[Resource]
|
A validated collection of resource instances. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object collection could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_json
classmethod
resource_validate_json(
json_data: str | bytes | bytearray,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Resource
Validate the given JSON data against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_data
|
str | bytes | bytearray
|
The JSON data to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Resource
|
A validated resource instance. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValidationError
|
If the object could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_json_many
classmethod
resource_validate_json_many(
json_data: str | bytes | bytearray,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Sequence[Resource]
Validate the given JSON data collection against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_data
|
str | bytes | bytearray
|
The JSON data collection to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Sequence[Resource]
|
A validated collection of resource instances. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValidationError
|
If the object collection could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_strings
classmethod
resource_validate_strings(
obj: Any,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Resource
Validate the given string object against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The string object to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Resource
|
A validated resource instance. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
resource_validate_strings_many
classmethod
resource_validate_strings_many(
obj: Any,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Sequence[Resource]
Validate the given string object collection against the resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The string object collection to validate. |
required |
strict
|
bool | None
|
Whether to enforce types strictly. |
None
|
context
|
dict[str, Any] | None
|
Extra variables to pass to the validator. |
None
|
Returns:
Type | Description |
---|---|
Sequence[Resource]
|
A validated collection of resource instances. |
Raises:
Type | Description |
---|---|
ValidationError
|
If the object collection could not be validated. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/resources.py
plateforme.core.mixins
This module provides resource mixin classes for the Plateforme framework.
Archivable
Archivable mixin for resource class.
FUTURE: Implement archivable mixin for resource class.
Auditable
Auditable mixin for resource class.
FIXME: Implement auditable mixin for resource class.
Encrypted
Encrypted mixin for resource class.
FUTURE: Implement encrypted mixin for resource class.