directory.types.directory_configuration
Attributes
Classes
Mixin that defines transparent propagation of change |
|
Allows the creation of types which add additional functionality |
Functions
|
Alphanumeric sorting by padding all numbers. |
Module Contents
- directory.types.directory_configuration.SAFE_FORMAT_TRANSLATORS: dict[type[object], collections.abc.Callable[[Any], str]][source]
- directory.types.directory_configuration.pad_numbers_in_chunks(text: str, padding: int = 8) str[source]
Alphanumeric sorting by padding all numbers.
- For example:
foobar-1-to-10 becomes foobar-0000000001-to-0000000010)
- See:
- class directory.types.directory_configuration.DirectoryConfiguration(title: str = None, lead: str | None = None, empty_notice: str | None = None, order: list[str] | None = None, keywords: list[str] | None = None, searchable: list[str] | None = None, display: dict[str, list[str]] | None = None, direction: Literal['asc', 'desc'] | None = None, link_pattern: str | None = None, link_title: str | None = None, link_visible: bool | None = None, thumbnail: str | None = None, address_block_title: str | None = None, show_as_thumbnails: list[str] | None = None, **kwargs: object)[source]
Bases:
sqlalchemy.ext.mutable.Mutable,StoredConfigurationMixin that defines transparent propagation of change events to a parent object.
See the example in mutable_scalars for usage information.
- fields = ('title', 'lead', 'empty_notice', 'order', 'keywords', 'searchable', 'display', 'direction',...[source]
- missing_fields(formcode: str | None) dict[str, list[str]][source]
Takes the given formcode and returns a dictionary with missing fields per configuration field. If the return-value is falsy, the configuration is valid.
For example:
>>> cfg = DirectoryConfiguration(title='[Name]') >>> cfg.missing_fields('Title = ___') {'title': ['Name']}
- classmethod coerce[T: sqlalchemy.ext.mutable.Mutable](key: str, value: T) T[source]
- classmethod coerce(key: str, value: object) NoReturn
Given a value, coerce it into the target type.
Can be overridden by custom subclasses to coerce incoming data into a particular type.
By default, raises
ValueError.This method is called in different scenarios depending on if the parent class is of type
Mutableor of typeMutableComposite. In the case of the former, it is called for both attribute-set operations as well as during ORM loading operations. For the latter, it is only called during attribute-set operations; the mechanics of thecomposite()construct handle coercion during load operations.- Parameters:
key – string name of the ORM-mapped attribute being set.
value – the incoming value.
- Returns:
the method should return the coerced value, or raise
ValueErrorif the coercion cannot be completed.
- class directory.types.directory_configuration.DirectoryConfigurationStorage(*args: Any, **kwargs: Any)[source]
Bases:
sqlalchemy.types.TypeDecorator[DirectoryConfiguration],sqlalchemy_utils.types.scalar_coercible.ScalarCoercibleAllows the creation of types which add additional functionality to an existing type.
This method is preferred to direct subclassing of SQLAlchemy’s built-in types as it ensures that all required functionality of the underlying type is kept in place.
Typical usage:
import sqlalchemy.types as types class MyType(types.TypeDecorator): """Prefixes Unicode values with "PREFIX:" on the way in and strips it off on the way out. """ impl = types.Unicode cache_ok = True def process_bind_param(self, value, dialect): return "PREFIX:" + value def process_result_value(self, value, dialect): return value[7:] def copy(self, **kw): return MyType(self.impl.length)
The class-level
implattribute is required, and can reference anyTypeEngineclass. Alternatively, theload_dialect_impl()method can be used to provide different type classes based on the dialect given; in this case, theimplvariable can referenceTypeEngineas a placeholder.The
TypeDecorator.cache_okclass-level flag indicates if this customTypeDecoratoris safe to be used as part of a cache key. This flag defaults toNonewhich will initially generate a warning when the SQL compiler attempts to generate a cache key for a statement that uses this type. If theTypeDecoratoris not guaranteed to produce the same bind/result behavior and SQL generation every time, this flag should be set toFalse; otherwise if the class produces the same behavior each time, it may be set toTrue. SeeTypeDecorator.cache_okfor further notes on how this works.Types that receive a Python type that isn’t similar to the ultimate type used may want to define the
TypeDecorator.coerce_compared_value()method. This is used to give the expression system a hint when coercing Python objects into bind parameters within expressions. Consider this expression:mytable.c.somecol + datetime.date(2009, 5, 15)
Above, if “somecol” is an
Integervariant, it makes sense that we’re doing date arithmetic, where above is usually interpreted by databases as adding a number of days to the given date. The expression system does the right thing by not attempting to coerce the “date()” value into an integer-oriented bind parameter.However, in the case of
TypeDecorator, we are usually changing an incoming Python type to something new -TypeDecoratorby default will “coerce” the non-typed side to be the same type as itself. Such as below, we define an “epoch” type that stores a date value as an integer:class MyEpochType(types.TypeDecorator): impl = types.Integer cache_ok = True epoch = datetime.date(1970, 1, 1) def process_bind_param(self, value, dialect): return (value - self.epoch).days def process_result_value(self, value, dialect): return self.epoch + timedelta(days=value)
Our expression of
somecol + datewith the above type will coerce the “date” on the right side to also be treated asMyEpochType.This behavior can be overridden via the
coerce_compared_value()method, which returns a type that should be used for the value of the expression. Below we set it such that an integer value will be treated as anInteger, and any other value is assumed to be a date and will be treated as aMyEpochType:def coerce_compared_value(self, op, value): if isinstance(value, int): return Integer() else: return self
Warning
Note that the behavior of coerce_compared_value is not inherited by default from that of the base type. If the
TypeDecoratoris augmenting a type that requires special logic for certain types of operators, this method must be overridden. A key example is when decorating the_postgresql.JSONand_postgresql.JSONBtypes; the default rules ofTypeEngine.coerce_compared_value()should be used in order to deal with operators like index operations:from sqlalchemy import JSON from sqlalchemy import TypeDecorator class MyJsonType(TypeDecorator): impl = JSON cache_ok = True def coerce_compared_value(self, op, value): return self.impl.coerce_compared_value(op, value)
Without the above step, index operations such as
mycol['foo']will cause the index value'foo'to be JSON encoded.Similarly, when working with the
ARRAYdatatype, the type coercion for index operations (e.g.mycol[5]) is also handled byTypeDecorator.coerce_compared_value(), where again a simple override is sufficient unless special rules are needed for particular operators:from sqlalchemy import ARRAY from sqlalchemy import TypeDecorator class MyArrayType(TypeDecorator): impl = ARRAY cache_ok = True def coerce_compared_value(self, op, value): return self.impl.coerce_compared_value(op, value)
- property python_type: type[DirectoryConfiguration][source]
Return the Python type object expected to be returned by instances of this type, if known.
Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like
intfor example), will return that type.If a return type is not defined, raises
NotImplementedError.Note that any type also accommodates NULL in SQL which means you can also get back
Nonefrom any type in practice.
- process_bind_param(value: DirectoryConfiguration | None, dialect: sqlalchemy.engine.Dialect) str | None[source]
Receive a bound parameter value to be converted.
Custom subclasses of
_types.TypeDecoratorshould override this method to provide custom behaviors for incoming data values. This method is called at statement execution time and is passed the literal Python data value which is to be associated with a bound parameter in the statement.The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic.
- Parameters:
value – Data to operate upon, of any type expected by this method in the subclass. Can be
None.dialect – the
Dialectin use.
See also
types_typedecorator
_types.TypeDecorator.process_result_value()
- process_result_value(value: str | None, dialect: sqlalchemy.engine.Dialect) DirectoryConfiguration | None[source]
Receive a result-row column value to be converted.
Custom subclasses of
_types.TypeDecoratorshould override this method to provide custom behaviors for data values being received in result rows coming from the database. This method is called at result fetching time and is passed the literal Python data value that’s extracted from a database result row.The operation could be anything desired to perform custom behavior, such as transforming or deserializing data.
- Parameters:
value – Data to operate upon, of any type expected by this method in the subclass. Can be
None.dialect – the
Dialectin use.
See also
types_typedecorator
_types.TypeDecorator.process_bind_param()