directory.types.directory_configuration

Module Contents

Classes

DirectoryConfigurationStorage

Allows the creation of types which add additional functionality

StoredConfiguration

DirectoryConfiguration

Mixin that defines transparent propagation of change

Functions

pad_numbers_in_chunks(→ str)

Alphanumeric sorting by padding all numbers.

Attributes

_Base

SAFE_FORMAT_TRANSLATORS

number_chunks

directory.types.directory_configuration._Base[source]
directory.types.directory_configuration.SAFE_FORMAT_TRANSLATORS[source]
directory.types.directory_configuration.number_chunks[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:

https://nedbatchelder.com/blog/200712/human_sorting.html

class directory.types.directory_configuration.DirectoryConfigurationStorage(*args, **kwargs)[source]

Bases: _Base, sqlalchemy_utils.types.scalar_coercible.ScalarCoercible

Allows 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

    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 impl attribute is required, and can reference any TypeEngine class. Alternatively, the load_dialect_impl() method can be used to provide different type classes based on the dialect given; in this case, the impl variable can reference TypeEngine as a placeholder.

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 Integer variant, 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 - TypeDecorator by 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

    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 + date with the above type will coerce the “date” on the right side to also be treated as MyEpochType.

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 an Integer, and any other value is assumed to be a date and will be treated as a MyEpochType:

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 TypeDecorator is 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.JSON and _postgresql.JSONB types; the default rules of TypeEngine.coerce_compared_value() should be used in order to deal with operators like index operations:

class MyJsonType(TypeDecorator):
    impl = postgresql.JSON

    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.

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 int for 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 None from any type in practice.

impl[source]
process_bind_param(value: DirectoryConfiguration | None, dialect: sqlalchemy.engine.Dialect) str | None[source]

Receive a bound parameter value to be converted.

Subclasses override this method to return the value that should be passed along to the underlying TypeEngine object, and from there to the DBAPI execute() method.

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.

This operation should be designed with the reverse operation in mind, which would be the process_result_value method of this class.

Parameters:
  • value – Data to operate upon, of any type expected by this method in the subclass. Can be None.

  • dialect – the Dialect in use.

process_result_value(value: str | None, dialect: sqlalchemy.engine.Dialect) DirectoryConfiguration | None[source]

Receive a result-row column value to be converted.

Subclasses should implement this method to operate on data fetched from the database.

Subclasses override this method to return the value that should be passed back to the application, given a value that is already processed by the underlying TypeEngine object, originally from the DBAPI cursor method fetchone() or similar.

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 Dialect in use.

This operation should be designed to be reversible by the “process_bind_param” method of this class.

class directory.types.directory_configuration.StoredConfiguration[source]
fields: tuple[str, Ellipsis][source]
to_dict() dict[str, Any][source]
to_json() str[source]
to_yaml() str[source]
classmethod from_json(text: str) typing_extensions.Self[source]
classmethod from_yaml(text: str) typing_extensions.Self[source]
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, StoredConfiguration

Mixin 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]
__setattr__(name: str, value: object) None[source]

Implement setattr(self, name, value).

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(key: str, value: _MutableT) _MutableT[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 Mutable or of type MutableComposite. 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 the composite() 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 ValueError if the coercion cannot be completed.

join(data: Mapping[str, Any], attribute: str, separator: str = '\n') str[source]
safe_format(fmt: str, data: Mapping[str, Any]) str[source]
for_safe_format(data: Mapping[str, Any]) dict[str, Any][source]
extract_name(data: Mapping[str, Any]) str[source]
extract_title(data: Mapping[str, Any]) str[source]
extract_lead(data: Mapping[str, Any]) str | None[source]
extract_order(data: Mapping[str, Any]) str[source]
extract_searchable(data: Mapping[str, Any]) str[source]
extract_keywords(data: Mapping[str, Any]) set[str] | None[source]