Selectors
plateforme.core.selectors
This module provides utilities for managing selectors used in resources within the Plateforme framework.
SelectorType
module-attribute
SelectorType = Type['BaseSelector[BaseResource]']
A type alias for a selector class.
SelectorConfig
SelectorConfig(
__owner: Any | None = None,
__defaults: dict[str, Any] | None = None,
__partial_init: bool = False,
/,
**data: Any,
)
Bases: ConfigWrapper
A selector 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
type_
class-attribute
instance-attribute
type_: str = ConfigField(
default="selector", frozen=True, init=False
)
The configuration owner type set to selector
. 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.
collection
class-attribute
instance-attribute
collection: bool | None = ConfigField(
default=None, frozen=True
)
Whether the selection should return a collection or a single instance
of the underlying resource class. Defaults to None
.
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
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 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 |
|
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
SelectorMeta
Bases: ABCMeta
, ConfigurableMeta
A metaclass for selector classes.
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
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 |
|
collect_resources
Collect selector resources from the given objects.
It collects the selector resources from the given bases and namespace by extracting the selector resource type from the original bases annotation if it is a generic subclass of the base selector class or metaclass, and from the resource 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[ResourceType]
|
A list of selector resource classes found in the given objects. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
parse_annotation
staticmethod
Parse resource and metadata update from a selector annotation.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
BaseSelector
Bases: dict[str, Any]
, Configurable[SelectorConfig]
, Generic[_T]
A base selector class to uniquely identify resource instances.
This class is used as a type annotation to define a resource selector for
a specific resource class. It is used as a proxy of the dict
type to
represent selection assignments for a specific resource type.
It can be inherited by applying a concrete selector resource class as a generic argument to the base selector class.
Note
The route auto-generation system will use this type hint to generate if needed the correct path parameter for the resource selector in the API routes.
Initialize a new selector.
It initializes a new resource selector with the provided assignment arguments and keyword arguments. The selector represents a dictionary of aliases and their associated values that identify resource instances.
To validate the selector against a resource class, the validate
method should be called with a specific resource and collection instead
of directly initializing the selector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
The provided selector assignments as a list of string
arguments with the following format |
()
|
**kwargs
|
Any
|
The provided selector assignments as a dictionary of assignment values with the aliases as keys. |
{}
|
Note
Only one wildcard entry *
is allowed within the selector
assignments. The wildcard entry is used to match any field alias in
a resource selector. If the wildcard entry is provided, it will
be matched against the selectors of the resource when specified to
determine the correct field alias.
A selector assignment value can be Deferred
to represent an
entry that should be inferred when initializing a resource
instance. Those entries can be filtered out when collecting the
selector assignment entries using the scope 'set'
.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resource
property
resource: type[_T]
The resource associated with the selector.
It is used to validate the selection assignments against this resource class and to generate the correct path parameter for the resource selector in the API routes.
config
config() -> SelectorConfig
build_query
build_query(
*,
filter_criteria: Filter | None = None,
sort_criteria: Sort | None = None,
options: Sequence[ExecutableOption] | None = None,
raise_errors: bool = True,
) -> Select[tuple[_T]]
Build a query for the selector.
Recursively builds a query for the selector by performing a join operation on the resource relationships found in the selector and filters the query based on the selector assignments. Optionally, the function can apply additional filter and sort criteria to the query.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_criteria
|
Filter | None
|
The filter criteria to apply to the query.
Defaults to |
None
|
sort_criteria
|
Sort | None
|
The sort criteria to apply to the query.
Defaults to |
None
|
options
|
Sequence[ExecutableOption] | None
|
The options to apply to the query.
Defaults to |
None
|
raise_errors
|
bool
|
Whether to raise errors when invalid attributes or
values are found in the selector assignments.
Defaults to |
True
|
Returns:
Type | Description |
---|---|
Select[tuple[_T]]
|
The built selector query with the applied filter and sort criteria. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
copy
copy() -> Self
entries
Return the selector assignments.
It returns the assignments dictionary based on the specified scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scope
|
Literal['all', 'deferred', 'set']
|
The scope of the selector assignments to return. It can be
either |
'all'
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A dictionary containing the selector assignments entries based on |
dict[str, Any]
|
the specified scope. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resolve
async
resolve(
__session: AsyncSession | None = None,
*,
limit: int | None = None,
options: Sequence[ExecutableOption] | None = None,
) -> Sequence[_T] | _T
Resolve the selector.
It resolves the selector against the associated resource class and returns the matching resource instances. If the selector is not associated with a collection, it returns a single resource instance.
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
|
limit
|
int | None
|
The maximum number of resource instances to return. If not
provided, all matching resource instances are returned.
Defaults to |
None
|
options
|
Sequence[ExecutableOption] | None
|
The options to apply to the query.
Defaults to |
None
|
Returns:
Type | Description |
---|---|
Sequence[_T] | _T
|
The resolved resource instances or single instance. |
Note
This method is similar to the resource manager get_one
and
get_many
database operations, enforcing at least one matching
resource instance for the latter.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resolve_lenient
async
resolve_lenient(
__session: AsyncSession | None = None,
*,
limit: int | None = None,
options: Sequence[ExecutableOption] | None = None,
) -> Sequence[_T] | _T | None
Resolve the selector.
It resolves the selector in a lenient way against the associated resource class and returns the matching resource instances. If the selector is not associated with a collection, it returns a single resource instance.
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
|
limit
|
int | None
|
The maximum number of resource instances to return. If not
provided, all matching resource instances are returned.
Defaults to |
None
|
options
|
Sequence[ExecutableOption] | None
|
The options to apply to the query.
Defaults to |
None
|
Returns:
Type | Description |
---|---|
Sequence[_T] | _T | None
|
The resolved resource instances or single instance. |
Note
This method is similar to the resource manager get
and get_many
database operations.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
create
classmethod
Create a new selector class for the given resource.
It constructs a new selector class for the provided resource class and
set the __config_resource__
attribute to the resource class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[_T]
|
The resource class to create the selector for. |
required |
Returns:
Type | Description |
---|---|
type[Self]
|
The new selector class for the given resource. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
create_type_adapter
classmethod
create_type_adapter(
alias: str, *, resource: type[_T] | None = None
) -> TypeAdapter[Any]
Create a type adapter for the given alias.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
alias
|
str
|
The resource alias to create the type adapter for. |
required |
resource
|
type[_T] | None
|
The resource associated with the selector. If not
provided, the resource is retrieved from the selector
class when available. Defaults to |
None
|
Returns:
Type | Description |
---|---|
TypeAdapter[Any]
|
The type adapter for the given alias. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
serialize
classmethod
serialize(
obj: dict[str, Any],
info: SerializationInfo | None = None,
*,
mode: Literal["json", "python"] | None = None,
scope: Literal["all", "deferred", "set"] = "all",
) -> dict[str, Any] | str
Serialize the selector to a string or a dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
dict[str, Any]
|
The selector to serialize. |
required |
info
|
SerializationInfo | None
|
Additional information to pass to the serializer.
Defaults to |
None
|
mode
|
Literal['json', 'python'] | None
|
The mode in which the serializer should run:
- If mode is |
None
|
scope
|
Literal['all', 'deferred', 'set']
|
The scope of the serialization to perform. It can be either
|
'all'
|
Returns:
Type | Description |
---|---|
dict[str, Any] | str
|
The serialized selector as a string if the serialization mode is |
dict[str, Any] | str
|
set to |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate
classmethod
validate(
obj: Any,
*,
resource: type[_T] | None = None,
update: dict[str, Any] | None = None,
validate_assignment: bool | None = None,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Self
Validate the given object against the selector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to validate. |
required |
resource
|
type[_T] | None
|
The resource associated with the selector. If not
provided, the resource is retrieved from the selector class.
Defaults to |
None
|
update
|
dict[str, Any] | None
|
Values to add/modify within the selector assignments.
Defaults to |
None
|
validate_assignment
|
bool | None
|
Whether to validate assignments against the
resource. Defaults to |
None
|
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 |
---|---|
ValidationError
|
If the object could not be validated. |
Returns:
Type | Description |
---|---|
Self
|
A validated selector instance. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate_resource
classmethod
Validate a resource against the selector.
It validates the provided resource against the selector configuration resource class. If no resource is provided, it retrieves the resource from the selector class configuration if available. Otherwise, it raises an error if no resource is found.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[_T] | None
|
The resource to validate. If not provided, the resource
is retrieved from the selector class configuration if
available. Defaults to |
None
|
Returns:
Type | Description |
---|---|
type[_T]
|
The validated resource class. |
Raises:
Type | Description |
---|---|
TypeError
|
If the resource type is invalid for the selector. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate_aliases
validate_aliases(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> str | None
Validate the selector aliases against the resource.
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
|
Returns:
Type | Description |
---|---|
str | None
|
The wildcard selector resolved alias if found. |
Raises:
Type | Description |
---|---|
ValidationError
|
If any alias is invalid. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
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 891 892 893 894 895 896 897 898 899 |
|
validate_assignments
validate_assignments(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
include: Iterable[str] | None = None,
exclude: Iterable[str] | None = None,
) -> None
Validate the selector assignments against the resource.
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
|
include
|
Iterable[str] | None
|
The aliases to include in the validation. If not provided,
all aliases are included. Defaults to |
None
|
exclude
|
Iterable[str] | None
|
The aliases to exclude from the validation. If not
provided, no aliases are excluded. Defaults to |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If any assignment is invalid. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
Key
Bases: BaseSelector[_T]
, Generic[_T]
A resource key to uniquely identify a resource instance.
This class is used as type annotation to define a resource key for a
specific resource class. It must be used with a generic argument to specify
the resource class associated with the underlying key within annotations,
or it should be directly instantiated with the validate
method by
providing a resource class as an argument.
Note
The route auto-generation system will use this type hint to generate if needed the correct path parameter for the resource selector in the API routes.
This class if final and is not meant to be inherited. Use the base selector class instead to create custom selector classes.
Initialize a new selector.
It initializes a new resource selector with the provided assignment arguments and keyword arguments. The selector represents a dictionary of aliases and their associated values that identify resource instances.
To validate the selector against a resource class, the validate
method should be called with a specific resource and collection instead
of directly initializing the selector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
The provided selector assignments as a list of string
arguments with the following format |
()
|
**kwargs
|
Any
|
The provided selector assignments as a dictionary of assignment values with the aliases as keys. |
{}
|
Note
Only one wildcard entry *
is allowed within the selector
assignments. The wildcard entry is used to match any field alias in
a resource selector. If the wildcard entry is provided, it will
be matched against the selectors of the resource when specified to
determine the correct field alias.
A selector assignment value can be Deferred
to represent an
entry that should be inferred when initializing a resource
instance. Those entries can be filtered out when collecting the
selector assignment entries using the scope 'set'
.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resource
property
resource: type[_T]
The resource associated with the selector.
It is used to validate the selection assignments against this resource class and to generate the correct path parameter for the resource selector in the API routes.
config
config() -> SelectorConfig
build_query
build_query(
*,
filter_criteria: Filter | None = None,
sort_criteria: Sort | None = None,
options: Sequence[ExecutableOption] | None = None,
raise_errors: bool = True,
) -> Select[tuple[_T]]
Build a query for the selector.
Recursively builds a query for the selector by performing a join operation on the resource relationships found in the selector and filters the query based on the selector assignments. Optionally, the function can apply additional filter and sort criteria to the query.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_criteria
|
Filter | None
|
The filter criteria to apply to the query.
Defaults to |
None
|
sort_criteria
|
Sort | None
|
The sort criteria to apply to the query.
Defaults to |
None
|
options
|
Sequence[ExecutableOption] | None
|
The options to apply to the query.
Defaults to |
None
|
raise_errors
|
bool
|
Whether to raise errors when invalid attributes or
values are found in the selector assignments.
Defaults to |
True
|
Returns:
Type | Description |
---|---|
Select[tuple[_T]]
|
The built selector query with the applied filter and sort criteria. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
copy
copy() -> Self
entries
Return the selector assignments.
It returns the assignments dictionary based on the specified scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scope
|
Literal['all', 'deferred', 'set']
|
The scope of the selector assignments to return. It can be
either |
'all'
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A dictionary containing the selector assignments entries based on |
dict[str, Any]
|
the specified scope. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
create
classmethod
Create a new selector class for the given resource.
It constructs a new selector class for the provided resource class and
set the __config_resource__
attribute to the resource class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[_T]
|
The resource class to create the selector for. |
required |
Returns:
Type | Description |
---|---|
type[Self]
|
The new selector class for the given resource. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
create_type_adapter
classmethod
create_type_adapter(
alias: str, *, resource: type[_T] | None = None
) -> TypeAdapter[Any]
Create a type adapter for the given alias.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
alias
|
str
|
The resource alias to create the type adapter for. |
required |
resource
|
type[_T] | None
|
The resource associated with the selector. If not
provided, the resource is retrieved from the selector
class when available. Defaults to |
None
|
Returns:
Type | Description |
---|---|
TypeAdapter[Any]
|
The type adapter for the given alias. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
serialize
classmethod
serialize(
obj: dict[str, Any],
info: SerializationInfo | None = None,
*,
mode: Literal["json", "python"] | None = None,
scope: Literal["all", "deferred", "set"] = "all",
) -> dict[str, Any] | str
Serialize the selector to a string or a dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
dict[str, Any]
|
The selector to serialize. |
required |
info
|
SerializationInfo | None
|
Additional information to pass to the serializer.
Defaults to |
None
|
mode
|
Literal['json', 'python'] | None
|
The mode in which the serializer should run:
- If mode is |
None
|
scope
|
Literal['all', 'deferred', 'set']
|
The scope of the serialization to perform. It can be either
|
'all'
|
Returns:
Type | Description |
---|---|
dict[str, Any] | str
|
The serialized selector as a string if the serialization mode is |
dict[str, Any] | str
|
set to |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate
classmethod
validate(
obj: Any,
*,
resource: type[_T] | None = None,
update: dict[str, Any] | None = None,
validate_assignment: bool | None = None,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Self
Validate the given object against the selector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to validate. |
required |
resource
|
type[_T] | None
|
The resource associated with the selector. If not
provided, the resource is retrieved from the selector class.
Defaults to |
None
|
update
|
dict[str, Any] | None
|
Values to add/modify within the selector assignments.
Defaults to |
None
|
validate_assignment
|
bool | None
|
Whether to validate assignments against the
resource. Defaults to |
None
|
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 |
---|---|
ValidationError
|
If the object could not be validated. |
Returns:
Type | Description |
---|---|
Self
|
A validated selector instance. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate_resource
classmethod
Validate a resource against the selector.
It validates the provided resource against the selector configuration resource class. If no resource is provided, it retrieves the resource from the selector class configuration if available. Otherwise, it raises an error if no resource is found.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[_T] | None
|
The resource to validate. If not provided, the resource
is retrieved from the selector class configuration if
available. Defaults to |
None
|
Returns:
Type | Description |
---|---|
type[_T]
|
The validated resource class. |
Raises:
Type | Description |
---|---|
TypeError
|
If the resource type is invalid for the selector. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate_aliases
validate_aliases(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> str | None
Validate the selector aliases against the resource.
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
|
Returns:
Type | Description |
---|---|
str | None
|
The wildcard selector resolved alias if found. |
Raises:
Type | Description |
---|---|
ValidationError
|
If any alias is invalid. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
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 891 892 893 894 895 896 897 898 899 |
|
validate_assignments
validate_assignments(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
include: Iterable[str] | None = None,
exclude: Iterable[str] | None = None,
) -> None
Validate the selector assignments against the resource.
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
|
include
|
Iterable[str] | None
|
The aliases to include in the validation. If not provided,
all aliases are included. Defaults to |
None
|
exclude
|
Iterable[str] | None
|
The aliases to exclude from the validation. If not
provided, no aliases are excluded. Defaults to |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If any assignment is invalid. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resolve
async
resolve(
__session: AsyncSession | None = None,
*,
options: Sequence[ExecutableOption] | None = None,
**kwargs: Any,
) -> _T
Resolve the key.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resolve_lenient
async
resolve_lenient(
__session: AsyncSession | None = None,
*,
options: Sequence[ExecutableOption] | None = None,
**kwargs: Any,
) -> _T | None
Resolve the key in a lenient way.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
KeyList
Bases: BaseSelector[_T]
, Generic[_T]
A resource key list to identify a list of resource instances.
This class is used as type annotation to define a resource key list for a
specific resource class. It must be used with a generic argument to specify
the resource class associated with the underlying key within annotations,
or it should be directly instantiated with the validate
method by
providing a resource class as an argument.
Note
The route auto-generation system will use this type hint to generate if needed the correct path parameter for the resource selector in the API routes.
This class if final and is not meant to be inherited. Use the base selector class instead to create custom selector classes.
Initialize a new selector.
It initializes a new resource selector with the provided assignment arguments and keyword arguments. The selector represents a dictionary of aliases and their associated values that identify resource instances.
To validate the selector against a resource class, the validate
method should be called with a specific resource and collection instead
of directly initializing the selector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
The provided selector assignments as a list of string
arguments with the following format |
()
|
**kwargs
|
Any
|
The provided selector assignments as a dictionary of assignment values with the aliases as keys. |
{}
|
Note
Only one wildcard entry *
is allowed within the selector
assignments. The wildcard entry is used to match any field alias in
a resource selector. If the wildcard entry is provided, it will
be matched against the selectors of the resource when specified to
determine the correct field alias.
A selector assignment value can be Deferred
to represent an
entry that should be inferred when initializing a resource
instance. Those entries can be filtered out when collecting the
selector assignment entries using the scope 'set'
.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resource
property
resource: type[_T]
The resource associated with the selector.
It is used to validate the selection assignments against this resource class and to generate the correct path parameter for the resource selector in the API routes.
config
config() -> SelectorConfig
build_query
build_query(
*,
filter_criteria: Filter | None = None,
sort_criteria: Sort | None = None,
options: Sequence[ExecutableOption] | None = None,
raise_errors: bool = True,
) -> Select[tuple[_T]]
Build a query for the selector.
Recursively builds a query for the selector by performing a join operation on the resource relationships found in the selector and filters the query based on the selector assignments. Optionally, the function can apply additional filter and sort criteria to the query.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_criteria
|
Filter | None
|
The filter criteria to apply to the query.
Defaults to |
None
|
sort_criteria
|
Sort | None
|
The sort criteria to apply to the query.
Defaults to |
None
|
options
|
Sequence[ExecutableOption] | None
|
The options to apply to the query.
Defaults to |
None
|
raise_errors
|
bool
|
Whether to raise errors when invalid attributes or
values are found in the selector assignments.
Defaults to |
True
|
Returns:
Type | Description |
---|---|
Select[tuple[_T]]
|
The built selector query with the applied filter and sort criteria. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
copy
copy() -> Self
entries
Return the selector assignments.
It returns the assignments dictionary based on the specified scope.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scope
|
Literal['all', 'deferred', 'set']
|
The scope of the selector assignments to return. It can be
either |
'all'
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A dictionary containing the selector assignments entries based on |
dict[str, Any]
|
the specified scope. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
create
classmethod
Create a new selector class for the given resource.
It constructs a new selector class for the provided resource class and
set the __config_resource__
attribute to the resource class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[_T]
|
The resource class to create the selector for. |
required |
Returns:
Type | Description |
---|---|
type[Self]
|
The new selector class for the given resource. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
create_type_adapter
classmethod
create_type_adapter(
alias: str, *, resource: type[_T] | None = None
) -> TypeAdapter[Any]
Create a type adapter for the given alias.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
alias
|
str
|
The resource alias to create the type adapter for. |
required |
resource
|
type[_T] | None
|
The resource associated with the selector. If not
provided, the resource is retrieved from the selector
class when available. Defaults to |
None
|
Returns:
Type | Description |
---|---|
TypeAdapter[Any]
|
The type adapter for the given alias. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
serialize
classmethod
serialize(
obj: dict[str, Any],
info: SerializationInfo | None = None,
*,
mode: Literal["json", "python"] | None = None,
scope: Literal["all", "deferred", "set"] = "all",
) -> dict[str, Any] | str
Serialize the selector to a string or a dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
dict[str, Any]
|
The selector to serialize. |
required |
info
|
SerializationInfo | None
|
Additional information to pass to the serializer.
Defaults to |
None
|
mode
|
Literal['json', 'python'] | None
|
The mode in which the serializer should run:
- If mode is |
None
|
scope
|
Literal['all', 'deferred', 'set']
|
The scope of the serialization to perform. It can be either
|
'all'
|
Returns:
Type | Description |
---|---|
dict[str, Any] | str
|
The serialized selector as a string if the serialization mode is |
dict[str, Any] | str
|
set to |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate
classmethod
validate(
obj: Any,
*,
resource: type[_T] | None = None,
update: dict[str, Any] | None = None,
validate_assignment: bool | None = None,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Self
Validate the given object against the selector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to validate. |
required |
resource
|
type[_T] | None
|
The resource associated with the selector. If not
provided, the resource is retrieved from the selector class.
Defaults to |
None
|
update
|
dict[str, Any] | None
|
Values to add/modify within the selector assignments.
Defaults to |
None
|
validate_assignment
|
bool | None
|
Whether to validate assignments against the
resource. Defaults to |
None
|
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 |
---|---|
ValidationError
|
If the object could not be validated. |
Returns:
Type | Description |
---|---|
Self
|
A validated selector instance. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate_resource
classmethod
Validate a resource against the selector.
It validates the provided resource against the selector configuration resource class. If no resource is provided, it retrieves the resource from the selector class configuration if available. Otherwise, it raises an error if no resource is found.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
type[_T] | None
|
The resource to validate. If not provided, the resource
is retrieved from the selector class configuration if
available. Defaults to |
None
|
Returns:
Type | Description |
---|---|
type[_T]
|
The validated resource class. |
Raises:
Type | Description |
---|---|
TypeError
|
If the resource type is invalid for the selector. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
validate_aliases
validate_aliases(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> str | None
Validate the selector aliases against the resource.
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
|
Returns:
Type | Description |
---|---|
str | None
|
The wildcard selector resolved alias if found. |
Raises:
Type | Description |
---|---|
ValidationError
|
If any alias is invalid. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
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 891 892 893 894 895 896 897 898 899 |
|
validate_assignments
validate_assignments(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
include: Iterable[str] | None = None,
exclude: Iterable[str] | None = None,
) -> None
Validate the selector assignments against the resource.
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
|
include
|
Iterable[str] | None
|
The aliases to include in the validation. If not provided,
all aliases are included. Defaults to |
None
|
exclude
|
Iterable[str] | None
|
The aliases to exclude from the validation. If not
provided, no aliases are excluded. Defaults to |
None
|
Raises:
Type | Description |
---|---|
ValidationError
|
If any assignment is invalid. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resolve
async
resolve(
__session: AsyncSession | None = None,
*,
limit: int | None = None,
options: Sequence[ExecutableOption] | None = None,
**kwargs: Any,
) -> Sequence[_T]
Resolve the key list.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
resolve_lenient
async
resolve_lenient(
__session: AsyncSession | None = None,
*,
limit: int | None = None,
options: Sequence[ExecutableOption] | None = None,
**kwargs: Any,
) -> Sequence[_T]
Resolve the key list in a lenient way.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/selectors.py
plateforme.core.expressions
This module provides utilities for managing expressions such as filters and sorts used in database and API queries within the Plateforme framework.
IncExKey
module-attribute
A type variable for inclusive and exclusive schema keys.
IncExValue
module-attribute
A type alias for inclusive and exclusive schema values.
IncExSet
module-attribute
A type alias for inclusive and exclusive schema of field sets.
IncExDict
module-attribute
IncExDict = Dict[IncExKey, IncExValue]
A type alias for inclusive and exclusive schema of field dictionaries.
IncExObj
module-attribute
A type alias for inclusive and exclusive schema of field objects.
IncExPredicate
module-attribute
IncExPredicate = Union[
Any,
Tuple[Sequence[Any], Any],
Tuple[Mapping[str, Any], Any],
Tuple[Sequence[Any], Mapping[str, Any], Any],
]
A type alias for inclusive and exclusive predicate values.
This type represents different ways to specify matching criteria for values. It supports both direct value matching and callable predicates with various argument patterns:
-
Any
Direct predicate where it checks whether the target matches the value, or is contained within the collection if the provided value is a list, set, or tuple, e.g.:42
or[1, 2, 3]
. -
Tuple[Sequence[Any], Any]
Callable predicate with positional arguments where it calls the function with the given positional arguments and matches against the value(s), e.g.:(['foo', 'bar'], 42)
or(['foo', 'bar'], [1, 2, 3])
. -
Tuple[Mapping[str, Any], Any]
Callable predicate with keyword arguments where it calls the function with the given keyword arguments and matches against the value(s), e.g.:({'min': 0, 'max': 100}, 42)
or({'foo': 'bar'}, [1, 2, 3])
. -
Tuple[Sequence[Any], Mapping[str, Any], Any]
Callable predicate with both positional and keyword arguments where it calls the function with both positional and keyword arguments and matches against the value(s), e.g.:(['foo', 'bar'], {'min': 0}, 42)
.
Note
For all forms, the last value can be either a single value or a collection
(list
, set
, tuple
) of values. The predicate matches if the result
equals the single value or is contained within the collection.
FilterDict
module-attribute
A type alias for a filter criteria dictionary.
FilterValue
module-attribute
FilterValue = Union[List[Condition], FilterDict]
A type alias for a filter criterion or nested criteria dictionary.
FilterVar
module-attribute
FilterVar = TypeVar('FilterVar', FilterDict, FilterValue)
A type variable for a filter dictionary or value.
SortValue
module-attribute
A type alias for a sort criterion value.
SortVar
module-attribute
A type variable for a sort list or a sort value.
IncEx
Inclusive and exclusive field schema factory.
This class is used to define the inclusive and exclusive field schema with a set or nested dictionary structure of integer field indexes or string field keys. For dictionaries, the values can be of type boolean to include or exclude the field based on the context.
Examples:
- The expression
{1, 2, 3}
when inclusive will only include the values from the first three fields. - The expression
{'user': {'id': True}, 'groups': True}
when exclusive will exclude the user id and groups field.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
from_args
classmethod
Create a new schema from the given arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
IncExKey | IncExObj[IncExKey]
|
The inclusive/exclusive set or nested dictionary structure of integer field indexes or string field keys. |
()
|
**kwargs
|
IncExValue
|
The inclusive/exclusive field keys with either boolean values to include or exclude the field based on the context, or set or nested dictionary structure of integer field indexes or string field keys. |
{}
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
|
ExpressionIssue
dataclass
Bases: Representation
An issue with an expression.
OperatorDefinition
dataclass
OperatorDefinition(
symbol: str,
types: tuple[type, ...],
sql: Callable[
[InstrumentedAttribute[Any], Any],
BinaryExpression[Any],
],
)
Bases: Representation
An operator definition.
types
instance-attribute
The types of values the operator can be applied to.
sql
instance-attribute
sql: Callable[
[InstrumentedAttribute[Any], Any], BinaryExpression[Any]
]
The SQL representation of the operator.
Operator
Bases: Enum
An enumeration of operators used in expressions.
EQUAL
class-attribute
instance-attribute
EQUAL = OperatorDefinition(
symbol="eq",
types=(float, int, str),
sql=lambda attr, comp: attr == comp,
)
Equal to (default)
NOT_EQUAL
class-attribute
instance-attribute
NOT_EQUAL = OperatorDefinition(
symbol="ne",
types=(float, int, str),
sql=lambda attr, comp: attr != comp,
)
Not equal to
GREATER_THAN
class-attribute
instance-attribute
GREATER_THAN = OperatorDefinition(
symbol="gt",
types=(float, int, str),
sql=lambda attr, comp: attr > comp,
)
Greater than
GREATER_THAN_OR_EQUAL
class-attribute
instance-attribute
GREATER_THAN_OR_EQUAL = OperatorDefinition(
symbol="ge",
types=(float, int, str),
sql=lambda attr, comp: attr >= comp,
)
Greater than or equal to
LESS_THAN
class-attribute
instance-attribute
LESS_THAN = OperatorDefinition(
symbol="lt",
types=(float, int, str),
sql=lambda attr, comp: attr < comp,
)
Less than
LESS_THAN_OR_EQUAL
class-attribute
instance-attribute
LESS_THAN_OR_EQUAL = OperatorDefinition(
symbol="le",
types=(float, int, str),
sql=lambda attr, comp: attr <= comp,
)
Less than or equal to
LIKE
class-attribute
instance-attribute
LIKE = OperatorDefinition(
symbol="like",
types=(str,),
sql=lambda attr, comp: like(
replace("*", "%") if isinstance(comp, str) else comp
),
)
Matching the like pattern
NOT_LIKE
class-attribute
instance-attribute
NOT_LIKE = OperatorDefinition(
symbol="nlike",
types=(str,),
sql=lambda attr, comp: ~like(
replace("*", "%") if isinstance(comp, str) else comp
),
)
Not matching the like pattern
IN
class-attribute
instance-attribute
IN = OperatorDefinition(
symbol="in",
types=(list,),
sql=lambda attr, comp: in_(comp),
)
In the list of
NOT_IN
class-attribute
instance-attribute
NOT_IN = OperatorDefinition(
symbol="nin",
types=(list,),
sql=lambda attr, comp: ~in_(comp),
)
Not in the list of
get
staticmethod
Get the operator associated with the given symbol.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
Symbol
Condition
dataclass
Bases: Representation
Condition options for a filter clause in a query.
operator
class-attribute
instance-attribute
The operator to filter the field.
reference
class-attribute
instance-attribute
Whether the value is a reference to another field.
apply
apply(
query: Select[Any],
attr: InstrumentedAttribute[Any],
*,
refs: dict[str, InstrumentedAttribute[Any]]
| None = None,
) -> Select[Any]
Apply the filtering condition to the given query and attribute.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query
|
Select[Any]
|
The query to apply the filtering condition to. |
required |
attr
|
InstrumentedAttribute[Any]
|
The attribute to apply the filtering condition to. |
required |
refs
|
dict[str, InstrumentedAttribute[Any]] | None
|
The reference attributes mapping used to resolve the condition reference value. |
None
|
Returns:
Type | Description |
---|---|
Select[Any]
|
The query with the filtering condition applied. |
Raises:
Type | Description |
---|---|
ValueError
|
When the condition reference value does not exist in the reference attributes mapping. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
Ordering
dataclass
Ordering(
direction: Literal["asc", "desc"] = "asc",
nulls: Literal["first", "last"] | None = None,
)
Bases: Representation
Options to sort a field in a query.
direction
class-attribute
instance-attribute
direction: Literal['asc', 'desc'] = 'asc'
The direction to sort the field.
nulls
class-attribute
instance-attribute
nulls: Literal['first', 'last'] | None = None
The position of null values in the sorted results.
apply
Apply the ordering options to the given query and attribute.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query
|
Select[Any]
|
The query to apply the ordering options to. |
required |
attr
|
InstrumentedAttribute[Any]
|
The attribute to apply the ordering options to. |
required |
Returns:
Type | Description |
---|---|
Select[Any]
|
The query with the ordering options applied. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
Filter
Filter(*criteria: FilterDict, **update: FilterValue | str)
Bases: FilterDict
A filter object to be used in a query.
It is used to filter the results of a query based on the given criteria. The filter criteria can be validated from nested dictionaries and list of conditions, or from raw strings formatted as a semicolon separated list of conditions and optionally prefixed with an operator, separated by a tilde character. Additionally, a filter condition can reference another field by prefixing the target field key value with a dollar character.
Attributes:
Name | Type | Description |
---|---|---|
references |
A list of reference attributes used within the filter criteria to resolve the reference values. |
Examples:
The expression {'price': 'gt~0;lt~1', 'cost': 'le~$price'}
will be parsed into:
>>> {
... 'price': [
... {'value': 0, 'operator': 'gt'},
... {'value': 1, 'operator': 'lt'},
... ],
... 'cost': [
... {'value': 'price', 'operator': 'le', 'reference': True},
... ],
... }
The expression {'user.name': 'like~Al*', user.groups*: 'foo'}
will be parsed into:
>>> {
... 'user': {
... 'name': [
... {'value': 'Al*', 'operator': 'like'},
... ],
... 'groups*': [
... {'value': 'foo', 'operator': 'eq'},
... ],
... },
... }
Initialize the filter object with the given criteria and updates.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
inspect
staticmethod
inspect(
value: FilterValue,
) -> tuple[list[ExpressionIssue], list[str]]
Inspect the filter criteria from the given value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
FilterValue
|
The filter criteria to inspect. |
required |
Returns:
Type | Description |
---|---|
list[ExpressionIssue]
|
A tuple with a list of issues with the filter criteria and a list |
list[str]
|
of references used in the filter criteria. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
merge
staticmethod
Copy and merge the given filter criteria.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
flatten
staticmethod
flatten(obj: FilterDict) -> FilterDict
Flatten a nested dictionary of filter criteria.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
unflatten
staticmethod
unflatten(obj: FilterDict) -> FilterDict
Unflatten a dictionary of filter criteria.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
parse_criterion
staticmethod
Parse the filter criterion conditions from the given string.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
parse_criteria
staticmethod
parse_criteria(string: str) -> FilterDict
Parse the filter criteria from the given string.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
validate
classmethod
Validate the filter criteria from the given object.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
Sort
Bases: SortList
A sort object to be used in a query.
It is used to store the sort criteria to order the results of a query. It can be validated from a raw string formatted as a comma or semicolon separated list of field key as alias fullnames; optionally prefixed with a plus or minus character for respectively ascending or descending order, and suffixed with direction and nulls clauses piped with a colon character.
The direction can be specified as asc
or desc
and the nulls as
first
and last
. By default, the direction is set to asc
and the
nulls to None
, i.e. the default database provider behavior.
Examples:
The expression price:nf
will be parsed into:
The expression user.name:asc:nl,-created_at
will be parsed into:
>>> [
... ('user.name', {'direction': 'asc', 'nulls': 'last'}),
... ('created_at', {'direction': 'desc', 'nulls': None}),
... ]
Initialize the sort object with the given criteria.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
inspect
staticmethod
inspect(criteria: SortList) -> list[ExpressionIssue]
Inspect the sort criterion key and options from the given criteria.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
criteria
|
SortList
|
The sort criteria to inspect. |
required |
Returns:
Type | Description |
---|---|
list[ExpressionIssue]
|
A list of issues with the sort criteria. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
parse_criterion
staticmethod
Parse the sort criterion key and options from the given string.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
parse_criteria
staticmethod
Parse the sort criteria from the given string.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/expressions.py
validate
classmethod
Validate the sort criteria from the given object.