directory.types.directory_configuration

Attributes

SAFE_FORMAT_TRANSLATORS

number_chunks

Classes

StoredConfiguration

DirectoryConfiguration

Mixin that defines transparent propagation of change

DirectoryConfigurationStorage

Allows the creation of types which add additional functionality

Functions

pad_numbers_in_chunks(→ str)

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.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.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) Self[source]
classmethod from_yaml(text: str) 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]
title = None[source]
lead = None[source]
empty_notice = None[source]
order = None[source]
keywords = None[source]
searchable = None[source]
display = None[source]
direction = None[source]
thumbnail = None[source]
address_block_title = None[source]
show_as_thumbnails = None[source]
__setattr__(name: str, value: object) None[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 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: collections.abc.Mapping[str, Any], attribute: str, separator: str = '\n') str[source]
safe_format(fmt: str, data: collections.abc.Mapping[str, Any]) str[source]
for_safe_format(data: collections.abc.Mapping[str, Any]) dict[str, Any][source]
extract_name(data: collections.abc.Mapping[str, Any]) str[source]
extract_title(data: collections.abc.Mapping[str, Any]) str[source]
extract_lead(data: collections.abc.Mapping[str, Any]) str | None[source]
extract_order(data: collections.abc.Mapping[str, Any]) str[source]
extract_searchable(data: collections.abc.Mapping[str, Any]) str[source]
extract_keywords(data: collections.abc.Mapping[str, Any]) set[str] | None[source]
class directory.types.directory_configuration.DirectoryConfigurationStorage(*args: Any, **kwargs: Any)[source]

Bases: sqlalchemy.types.TypeDecorator[DirectoryConfiguration], 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

    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 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.

The TypeDecorator.cache_ok class-level flag indicates if this custom TypeDecorator is safe to be used as part of a cache key. This flag defaults to None which will initially generate a warning when the SQL compiler attempts to generate a cache key for a statement that uses this type. If the TypeDecorator is not guaranteed to produce the same bind/result behavior and SQL generation every time, this flag should be set to False; otherwise if the class produces the same behavior each time, it may be set to True. See TypeDecorator.cache_ok for 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 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

    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 + 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:

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 ARRAY datatype, the type coercion for index operations (e.g. mycol[5]) is also handled by TypeDecorator.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)
impl[source]
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.

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

See also

types_typedecorator

_types.TypeDecorator.process_bind_param()