API Reference


Declarative ORM

SQLAthanor provides a drop-in replacement for SQLAlchemy’s declarative_base() function and decorators, which can either be used as a base for your SQLAlchemy models directly or can be mixed into your SQLAlchemy models.

See also

It is BaseModel which exposes the methods and properties that enable serialization and de-serialization support.

For more information, please see:

BaseModel

class BaseModel(*args, **kwargs)[source]

Base class that establishes shared methods, attributes, and properties.

When constructing your ORM models, inherit from (or mixin) this class to add support for serialization and de-serialization.

Note

It is this class which adds SQLAthanor’s methods and properties to your SQLAlchemy model.

If your SQLAlchemy models do not inherit from this class, then they will not actually support serialization or de-serialization.

You can construct your declarative models using three approaches:

By inheriting or mixing in BaseModel directly as shown in the examples below.

from sqlathanor import BaseModel

# EXAMPLE 1: As a direct parent class for your model.
class MyModel(BaseModel):

    # Standard SQLAlchemy declarative model definition goes here.

# EXAMPLE 2: As a mixin parent for your model.
class MyBaseModel(object):

    # An existing base model that you have developed.

class MyModel(MyBaseModel, BaseModel):

    # Standard SQLAlchemy declarative model definition goes here.

By calling the declarative_base() function from SQLAthanor:

from sqlathanor import declarative_base

MyBaseModel = declarative_base()

By decorating your base model class with the @as_declarative decorator:

from sqlathanor import as_declarative

@as_declarative
class MyBaseModel(object):

    # Standard SQLAlchemy declarative model definition goes here.
classmethod configure_serialization(configs=None, attributes=None, supports_csv=False, supports_json=False, supports_yaml=False, supports_dict=False, on_serialize=None, on_deserialize=None, config_set=None)

Apply configuration settings to the model class (overwrites entire configuration).

Tip

For this method, the configuration settings applied in configs receive priority over a configuration specified in keyword arguments.

This means that if an attribute is configured in both configs and attributes, the configuration in configs will apply.

Parameters:
  • configs (iterable of AttributeConfiguration / None) – Collection of AttributeConfiguration objects to apply to the class. Defaults to None.
  • attributes (iterable of str / None) – Collection of model attribute names to which a configuration will be applied. Defaults to None.
  • supports_csv (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from CSV format.

    If True, can be serialized to CSV and de-serialized from CSV. If False, will not be included when serialized to CSV and will be ignored if present in a de-serialized CSV.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False.

  • supports_json (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from JSON format.

    If True, can be serialized to JSON and de-serialized from JSON. If False, will not be included when serialized to JSON and will be ignored if present in a de-serialized JSON.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False.

  • supports_yaml (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from YAML format.

    If True, can be serialized to YAML and de-serialized from YAML. If False, will not be included when serialized to YAML and will be ignored if present in a de-serialized YAML.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False.

  • supports_dict (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized to a Python dict.

    If True, can be serialized to dict and de-serialized from a dict. If False, will not be included when serialized to dict and will be ignored if present in a de-serialized dict.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False.

  • on_deserialize (callable / dict with formats as keys and values as callables / None) –

    A function that will be called when attempting to assign a de-serialized value to the column. This is intended to either coerce the value being assigned to a form that is acceptable by the column, or raise an exception if it cannot be coerced.

    Tip

    If you need to execute different on_deserialize functions for different formats, you can also supply a dict:

    on_deserialize = {
      'csv': csv_on_deserialize_callable,
      'json': json_on_deserialize_callable,
      'yaml': yaml_on_deserialize_callable,
      'dict': dict_on_deserialize_callable
    }
    

    If False, will clear the current configuration to apply the default.

    If None, will retain whatever configuration is currently applied. Defaults to None

    Tip

    To clear the on_deserialize function, you can either supply a value of False or pass a dict with particular formats set to None:

    on_deserialize = {
      'csv': None,
      'json': None,
      'yaml': None,
      'dict': None
    }
    
    # is equivalent to:
    
    on_deserialize = False
    

    This will revert the on_deserialize function to the attribute’s default on_deserialize function based on its data type.

  • on_serialize (callable / dict with formats as keys and values as callables / None / False) –

    A function that will be called when attempting to serialize a value from the column.

    Tip

    If you need to execute different on_serialize functions for different formats, you can also supply a dict:

    on_serialize = {
      'csv': csv_on_serialize_callable,
      'json': json_on_serialize_callable,
      'yaml': yaml_on_serialize_callable,
      'dict': dict_on_serialize_callable
    }
    

    If False, will clear the current configuration to apply the default configuration.

    If None, will retain whatever configuration is currently applied. Defaults to None

    Tip

    To clear the on_serialize function, you need to pass False or a dict with particular formats set to None:

    on_serialize = {
      'csv': None,
      'json': None,
      'yaml': None,
      'dict': None
    }
    
    # is equivalent to
    
    on_serialize = False
    

    This will revert the on_serialize function to the attribute’s default on_serialize function based on its data type.

  • config_set (str / None) – If not None, will apply configs to the configuration set named. If the class does not use pre-existing configuration sets, will switch the class’ meta configuration to use configuration sets, with any pre-existing configuration set assigned to a set named _original. Defaults to None.
classmethod does_support_serialization(attribute, from_csv=None, to_csv=None, from_json=None, to_json=None, from_yaml=None, to_yaml=None, from_dict=None, to_dict=None, config_set=None)

Indicate whether attribute supports serialization/deserializtion.

Parameters:
  • attribute (str) – The name of the attribute whose serialization support should be confirmed.
  • from_csv (bool / None) – If True, includes attribute names that can be de-serialized from CSV strings. If False, includes attribute names that cannot be de-serialized from CSV strings. If None, will not include attributes based on CSV de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_csv (bool / None) – If True, includes attribute names that can be serialized to CSV strings. If False, includes attribute names that cannot be serialized to CSV strings. If None, will not include attributes based on CSV serialization support (but may include them based on other parameters). Defaults to None.
  • from_json (bool / None) – If True, includes attribute names that can be de-serialized from JSON strings. If False, includes attribute names that cannot be de-serialized from JSON strings. If None, will not include attributes based on JSON de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_json (bool / None) – If True, includes attribute names that can be serialized to JSON strings. If False, includes attribute names that cannot be serialized to JSON strings. If None, will not include attributes based on JSON serialization support (but may include them based on other parameters). Defaults to None.
  • from_yaml (bool / None) – If True, includes attribute names that can be de-serialized from YAML strings. If False, includes attribute names that cannot be de-serialized from YAML strings. If None, will not include attributes based on YAML de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_yaml (bool / None) – If True, includes attribute names that can be serialized to YAML strings. If False, includes attribute names that cannot be serialized to YAML strings. If None, will not include attributes based on YAML serialization support (but may include them based on other parameters). Defaults to None.
  • from_dict (bool / None) – If True, includes attribute names that can be de-serialized from dict objects. If False, includes attribute names that cannot be de-serialized from dict objects. If None, will not include attributes based on dict de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_dict – If True, includes attribute names that can be serialized to dict objects. If False, includes attribute names that cannot be serialized to dict objects. If None, will not include attributes based on dict serialization support (but may include them based on other parameters). Defaults to None.
  • config_set (str / None) – If not None, will determine serialization support within the indicated configuration set. Defaults to None.
Returns:

True if the attribute’s serialization support matches, False if not, and None if no serialization support was specified.

Return type:

bool / None

Raises:
dump_to_csv(include_header=False, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', config_set=None)

Retrieve a CSV representation of the object, with all attributes serialized regardless of configuration.

Caution

Nested objects (such as relationships or association proxies) will not be serialized.

Note

This method ignores any display_name contributed on the AttributeConfiguration.

Parameters:
  • include_header (bool) – If True, will include a header row with column labels. If False, will not include a header row. Defaults to True.
  • delimiter (str) – The delimiter used between columns. Defaults to |.
  • wrap_all_strings (bool) – If True, wraps any string data in the wrapper_character. If None, only wraps string data if it contains the delimiter. Defaults to False.
  • null_text (str) – The text value to use in place of empty values. Only applies if wrap_empty_values is True. Defaults to 'None'.
  • wrapper_character (str) – The string used to wrap string values when wrapping is necessary. Defaults to '.
  • double_wrapper_character_when_nested (bool) – If True, will double the wrapper_character when it is found inside a column value. If False, will precede the wrapper_character by the escape_character when it is found inside a column value. Defaults to False.
  • escape_character (str) – The character to use when escaping nested wrapper characters. Defaults to \.
  • line_terminator (str) – The character used to mark the end of a line. Defaults to \r\n.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Returns:

Data from the object in CSV format ending in a newline (\n).

Return type:

str

dump_to_dict(max_nesting=0, current_nesting=0, config_set=None)

Return a OrderedDict representation of the object, with all attributes regardless of configuration.

Caution

Nested objects (such as relationships or association proxies) will not be serialized.

Parameters:
  • max_nesting (int) – The maximum number of levels that the resulting OrderedDict object can be nested. If set to 0, will not nest other serializable objects. Defaults to 0.
  • current_nesting (int) – The current nesting level at which the dict representation will reside. Defaults to 0.
  • config_set (str / None) – If not None, the named configuration set to use when processing the input. Defaults to None.
Returns:

A OrderedDict representation of the object.

Return type:

OrderedDict

Raises:
dump_to_json(max_nesting=0, current_nesting=0, serialize_function=None, config_set=None, **kwargs)

Return a JSON representation of the object, with all attributes regardless of configuration.

Caution

Nested objects (such as relationships or association proxies) will not be serialized.

Parameters:
  • max_nesting (int) – The maximum number of levels that the resulting JSON object can be nested. If set to 0, will not nest other serializable objects. Defaults to 0.
  • current_nesting (int) – The current nesting level at which the dict representation will reside. Defaults to 0.
  • serialize_function (callable / None) –

    Optionally override the default JSON serializer. Defaults to None, which applies the default simplejson JSON serializer.

    Note

    Use the serialize_function parameter to override the default JSON serializer.

    A valid serialize_function is expected to accept a single dict and return a str, similar to simplejson.dumps().

    If you wish to pass additional arguments to your serialize_function pass them as keyword arguments (in kwargs).

  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
  • kwargs (keyword arguments) – Optional keyword parameters that are passed to the JSON serializer function. By default, these are options which are passed to simplejson.dumps().
Returns:

A str with the JSON representation of the object.

Return type:

str

Raises:
dump_to_yaml(max_nesting=0, current_nesting=0, serialize_function=None, config_set=None, **kwargs)

Return a YAML representation of the object with all attributes, regardless of configuration.

Caution

Nested objects (such as relationships or association proxies) will not be serialized.

Parameters:
  • max_nesting (int) – The maximum number of levels that the resulting object can be nested. If set to 0, will not nest other serializable objects. Defaults to 0.
  • current_nesting (int) – The current nesting level at which the representation will reside. Defaults to 0.
  • serialize_function (callable / None) –

    Optionally override the default YAML serializer. Defaults to None, which calls the default yaml.dump() function from the PyYAML library.

    Note

    Use the serialize_function parameter to override the default YAML serializer.

    A valid serialize_function is expected to accept a single dict and return a str, similar to yaml.dump().

    If you wish to pass additional arguments to your serialize_function pass them as keyword arguments (in kwargs).

  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
  • kwargs (keyword arguments) – Optional keyword parameters that are passed to the YAML serializer function. By default, these are options which are passed to yaml.dump().
Returns:

A str with the JSON representation of the object.

Return type:

str

Raises:
classmethod get_attribute_serialization_config(attribute, config_set=None)

Retrieve the AttributeConfiguration for attribute.

Parameters:
  • attribute (str) – The attribute/column name whose serialization configuration should be returned.
  • config_set (str / None) – If not None, will return the AttributeConfiguration object for attribute that is contained within the named set. Defaults to None.
Returns:

The AttributeConfiguration for attribute.

Return type:

AttributeConfiguration

Raises:
  • ConfigurationError – if config_set is not empty and there are no configuration sets defined on cls or if there are configuration sets defined but no config_set is specified
  • ValueError – if config_set is not defined within __serialization__
classmethod get_csv_column_names(deserialize=True, serialize=True, config_set=None)

Retrieve a list of CSV column names.

Parameters:
  • deserialize (bool) – If True, returns columns that support de-serialization. If False, returns columns that do not support deserialization. If None, does not take deserialization into account. Defaults to True.
  • serialize (bool) – If True, returns columns that support serialization. If False, returns columns that do not support serialization. If None, does not take serialization into account. Defaults to True.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Returns:

List of CSV column names, sorted according to their configuration.

Return type:

list of str

get_csv_data(delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', config_set=None)

Return the CSV representation of the model instance (record).

Parameters:
  • delimiter (str) – The delimiter used between columns. Defaults to |.
  • wrap_all_strings (bool) – If True, wraps any string data in the wrapper_character. If None, only wraps string data if it contains the delimiter. Defaults to False.
  • null_text (str) – The text value to use in place of empty values. Only applies if wrap_empty_values is True. Defaults to 'None'.
  • wrapper_character (str) – The string used to wrap string values when wrapping is necessary. Defaults to '.
  • double_wrapper_character_when_nested (bool) – If True, will double the wrapper_character when it is found inside a column value. If False, will precede the wrapper_character by the escape_character when it is found inside a column value. Defaults to False.
  • escape_character (str) – The character to use when escaping nested wrapper characters. Defaults to \.
  • line_terminator (str) – The character used to mark the end of a line. Defaults to \r\n.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Returns:

Data from the object in CSV format ending in line_terminator.

Return type:

str

classmethod get_csv_header(deserialize=None, serialize=True, delimiter='|', wrap_all_strings=False, wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', config_set=None)

Retrieve a header string for a CSV representation of the model.

Parameters:
  • attributes (list of str) – List of model attributes to include.
  • delimiter (str) – The character(s) to utilize between columns. Defaults to a pipe (|).
  • wrap_all_strings (bool) – If True, wraps any string data in the wrapper_character. If None, only wraps string data if it contains the delimiter. Defaults to False.
  • null_text (str) – The text value to use in place of empty values. Only applies if wrap_empty_values is True. Defaults to 'None'.
  • null_text – The text value to use in place of empty values. Only applies if wrap_empty_values is True. Defaults to 'None'.
  • wrapper_character (str) – The string used to wrap string values when wrapping is necessary. Defaults to '.
  • double_wrapper_character_when_nested (bool) – If True, will double the wrapper_character when it is found inside a column value. If False, will precede the wrapper_character by the escape_character when it is found inside a column value. Defaults to False.
  • escape_character (str) – The character to use when escaping nested wrapper characters. Defaults to \.
  • line_terminator (str) – The character used to mark the end of a line. Defaults to \r\n.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Returns:

A string ending in line_terminator with the model’s CSV column names listed, separated by the delimiter.

Return type:

str

classmethod get_csv_serialization_config(deserialize=True, serialize=True, config_set=None)

Retrieve the CSV serialization configurations that apply for this object.

Parameters:
  • deserialize (bool / None) – If True, returns configurations for attributes that can be de-serialized from CSV strings. If False, returns configurations for attributes that cannot be de-serialized from CSV strings. If None, ignores de-serialization configuration when determining which attribute configurations to return. Defaults to None.
  • serialize (bool / None) – If True, returns configurations for attributes that can be serialized to CSV strings. If False, returns configurations for attributes that cannot be serialized to CSV strings. If None, ignores serialization configuration when determining which attribute configurations to return. Defaults to None.
  • config_set (str / None) – If not None, the named configuration set whose CSV serialization configuration should be returned. Defaults to None.
Returns:

Set of attribute serialization configurations that match the arguments supplied.

Return type:

list of AttributeConfiguration

Raises:
classmethod get_dict_serialization_config(deserialize=True, serialize=True, config_set=None)

Retrieve the dict serialization configurations that apply for this object.

Parameters:
  • deserialize (bool / None) – If True, returns configurations for attributes that can be de-serialized from dict objects. If False, returns configurations for attributes that cannot be de-serialized from dict objects. If None, ignores de-serialization configuration when determining which attribute configurations to return. Defaults to None.
  • serialize (bool / None) – If True, returns configurations for attributes that can be serialized to dict objects. If False, returns configurations for attributes that cannot be serialized to dict objects. If None, ignores serialization configuration when determining which attribute configurations to return. Defaults to None.
  • config_set (str / None) – If not None, the named configuration set whose serialization configuration should be returned. Defaults to None.
Returns:

Set of attribute serialization configurations that match the arguments supplied.

Return type:

list of AttributeConfiguration

classmethod get_json_serialization_config(deserialize=True, serialize=True, config_set=None)

Retrieve the JSON serialization configurations that apply for this object.

Parameters:
  • deserialize (bool / None) – If True, returns configurations for attributes that can be de-serialized from JSON strings. If False, returns configurations for attributes that cannot be de-serialized from JSON strings. If None, ignores de-serialization configuration when determining which attribute configurations to return. Defaults to None.
  • serialize (bool / None) – If True, returns configurations for attributes that can be serialized to JSON strings. If False, returns configurations for attributes that cannot be serialized to JSON strings. If None, ignores serialization configuration when determining which attribute configurations to return. Defaults to None.
  • config_set (str / None) – If not None, the named configuration set whose serialization configuration should be returned. Defaults to None.
Returns:

Set of attribute serialization configurations that match the arguments supplied.

Return type:

list of AttributeConfiguration

classmethod get_primary_key_column_names()

Retrieve the column names for the model’s primary key columns.

Return type:list of str
classmethod get_primary_key_columns()

Retrieve the model’s primary key columns.

Returns:list of Column objects corresponding to the table’s primary key(s).
Return type:list of Column
classmethod get_serialization_config(from_csv=None, to_csv=None, from_json=None, to_json=None, from_yaml=None, to_yaml=None, from_dict=None, to_dict=None, exclude_private=True, config_set=None)

Retrieve a list of AttributeConfiguration objects corresponding to attributes whose values can be serialized from/to CSV, JSON, YAML, etc.

Parameters:
  • from_csv (bool / None) – If True, includes attribute names that can be de-serialized from CSV strings. If False, includes attribute names that cannot be de-serialized from CSV strings. If None, will not include attributes based on CSV de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_csv (bool / None) – If True, includes attribute names that can be serialized to CSV strings. If False, includes attribute names that cannot be serialized to CSV strings. If None, will not include attributes based on CSV serialization support (but may include them based on other parameters). Defaults to None.
  • from_json (bool / None) – If True, includes attribute names that can be de-serialized from JSON strings. If False, includes attribute names that cannot be de-serialized from JSON strings. If None, will not include attributes based on JSON de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_json (bool / None) – If True, includes attribute names that can be serialized to JSON strings. If False, includes attribute names that cannot be serialized to JSON strings. If None, will not include attributes based on JSON serialization support (but may include them based on other parameters). Defaults to None.
  • from_yaml (bool / None) – If True, includes attribute names that can be de-serialized from YAML strings. If False, includes attribute names that cannot be de-serialized from YAML strings. If None, will not include attributes based on YAML de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_yaml (bool / None) – If True, includes attribute names that can be serialized to YAML strings. If False, includes attribute names that cannot be serialized to YAML strings. If None, will not include attributes based on YAML serialization support (but may include them based on other parameters). Defaults to None.
  • from_dict (bool / None) – If True, includes attribute names that can be de-serialized from dict objects. If False, includes attribute names that cannot be de-serialized from dict objects. If None, will not include attributes based on dict de-serialization support (but may include them based on other parameters). Defaults to None.
  • to_dict – If True, includes attribute names that can be serialized to dict objects. If False, includes attribute names that cannot be serialized to dict objects. If None, will not include attributes based on dict serialization support (but may include them based on other parameters). Defaults to None.
  • exclude_private (bool) – If True, will exclude private attributes whose names begin with a single underscore. Defaults to True.
  • config_set (str / None) – If not None, will return those AttributeConfiguration objects that are contained within the named set. Defaults to None.
Returns:

List of attribute configurations.

Return type:

list of AttributeConfiguration

Raises:
classmethod get_yaml_serialization_config(deserialize=True, serialize=True, config_set=None)

Retrieve the YAML serialization configurations that apply for this object.

Parameters:
  • deserialize (bool / None) – If True, returns configurations for attributes that can be de-serialized from YAML strings. If False, returns configurations for attributes that cannot be de-serialized from YAML strings. If None, ignores de-serialization configuration when determining which attribute configurations to return. Defaults to None.
  • serialize (bool / None) – If True, returns configurations for attributes that can be serialized to YAML strings. If False, returns configurations for attributes that cannot be serialized to YAML strings. If None, ignores serialization configuration when determining which attribute configurations to return. Defaults to None.
  • config_set (str / None) – If not None, the named configuration set whose serialization configuration should be returned. Defaults to None.
Returns:

Set of attribute serialization configurations that match the arguments supplied.

Return type:

list of AttributeConfiguration

classmethod new_from_csv(csv_data, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', config_set=None)

Create a new model instance from a CSV record.

Tip

Unwrapped empty column values are automatically interpreted as null (None).

Parameters:
  • csv_data (str / Path-like object) – The CSV data. If a Path-like object, will read the first record from a file that is assumed to include a header row. If a str and has more than one record (line), will assume the first line is a header row.
  • delimiter (str) – The delimiter used between columns. Defaults to |.
  • wrapper_character (str) – The string used to wrap string values when wrapping is applied. Defaults to '.
  • null_text (str) – The string used to indicate an empty value if empty values are wrapped. Defaults to None.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Returns:

A model instance created from the record.

Return type:

model instance

Raises:
classmethod new_from_dict(input_data, error_on_extra_keys=True, drop_extra_keys=False, config_set=None)

Update the model instance from data in a dict object.

Parameters:
  • input_data (dict) – The input dict
  • error_on_extra_keys (bool) –

    If True, will raise an error if an unrecognized key is found in input_data. If False, will either drop or include the extra key in the result, as configured in the drop_extra_keys parameter. Defaults to True.

    Warning

    Be careful setting error_on_extra_keys to False.

    This method’s last step passes the keys/values of the processed input data to your model’s __init__() method.

    If your instance’s __init__() method does not support your extra keys, it will likely raise a TypeError.

  • drop_extra_keys (bool) – If True, will omit unrecognized top-level keys from the resulting dict. If False, will include unrecognized keys or raise an error based on the configuration of the error_on_extra_keys parameter. Defaults to False.
  • config_set (str / None) – If not None, the named configuration set to use when processing the input. Defaults to None.
Raises:
  • ExtraKeyError – if error_on_extra_keys is True and input_data contains top-level keys that are not recognized as attributes for the instance model.
  • DeserializationError – if input_data is not a dict or JSON object serializable to a dict or if input_data is empty.
classmethod new_from_json(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)

Create a new model instance from data in JSON.

Parameters:
  • input_data (str or Path-like object) –

    The JSON data to de-serialize.

    Note

    If input_data points to a file, and the file contains a list of JSON objects, the first JSON object will be considered.

  • deserialize_function (callable / None) –

    Optionally override the default JSON deserializer. Defaults to None, which calls the default simplejson.loads() function from the doc:simplejson <simplejson:index> library.

    Note

    Use the deserialize_function parameter to override the default JSON deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to simplejson.loads().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in kwargs).

  • error_on_extra_keys (bool) –

    If True, will raise an error if an unrecognized key is found in input_data. If False, will either drop or include the extra key in the result, as configured in the drop_extra_keys parameter. Defaults to True.

    Warning

    Be careful setting error_on_extra_keys to False.

    This method’s last step passes the keys/values of the processed input data to your model’s __init__() method.

    If your instance’s __init__() method does not support your extra keys, it will likely raise a TypeError.

  • drop_extra_keys (bool) – If True, will ignore unrecognized top-level keys in input_data. If False, will include unrecognized keys or raise an error based on the configuration of the error_on_extra_keys parameter. Defaults to False.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
  • kwargs (keyword arguments) – Optional keyword parameters that are passed to the JSON deserializer function. By default, these are options which are passed to simplejson.loads().
Raises:
  • ExtraKeyError – if error_on_extra_keys is True and input_data contains top-level keys that are not recognized as attributes for the instance model.
  • DeserializationError – if input_data is not a dict or JSON object serializable to a dict or if input_data is empty.
classmethod new_from_yaml(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)

Create a new model instance from data in YAML.

Parameters:
  • input_data (str / Path-like object) – The YAML data to de-serialize. May be either a str or a Path-like object to a YAML file.
  • deserialize_function (callable / None) –

    Optionally override the default YAML deserializer. Defaults to None, which calls the default yaml.safe_load() function from the PyYAML library.

    Note

    Use the deserialize_function parameter to override the default YAML deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to yaml.safe_load().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in kwargs).

  • error_on_extra_keys (bool) –

    If True, will raise an error if an unrecognized key is found in input_data. If False, will either drop or include the extra key in the result, as configured in the drop_extra_keys parameter. Defaults to True.

    Warning

    Be careful setting error_on_extra_keys to False.

    This method’s last step passes the keys/values of the processed input data to your model’s __init__() method.

    If your instance’s __init__() method does not support your extra keys, it will likely raise a TypeError.

  • drop_extra_keys (bool) – If True, will ignore unrecognized top-level keys in input_data. If False, will include unrecognized keys or raise an error based on the configuration of the error_on_extra_keys parameter. Defaults to False.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Raises:
  • ExtraKeyError – if error_on_extra_keys is True and input_data contains top-level keys that are not recognized as attributes for the instance model.
  • DeserializationError – if input_data is not a dict or JSON object serializable to a dict or if input_data is empty.
classmethod set_attribute_serialization_config(attribute, config=None, supports_csv=None, csv_sequence=None, supports_json=None, supports_yaml=None, supports_dict=None, on_deserialize=None, on_serialize=None, config_set=None)

Set the serialization/de-serialization configuration for attribute.

Note

Supplying keyword arguments like supports_csv or supports_json will override any configuration set in config.

Parameters:
  • attribute (str) – The name of the model attribute whose serialization/de-serialization configuration is to be configured.
  • config (AttributeConfiguration / None) – The AttributeConfiguration to apply. If None, will set particular values based on their corresponding keyword arguments.
  • supports_csv (bool / tuple of form (inbound: bool, outbound: bool) / None) –

    Determines whether the column can be serialized to or de-serialized from CSV format.

    If True, can be serialized to CSV and de-serialized from CSV. If False, will not be included when serialized to CSV and will be ignored if present in a de-serialized CSV.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    If None, will retain whatever configuration is currently applied. Defaults to None

  • supports_json (bool / tuple of form (inbound: bool, outbound: bool) / None) –

    Determines whether the column can be serialized to or de-serialized from JSON format.

    If True, can be serialized to JSON and de-serialized from JSON. If False, will not be included when serialized to JSON and will be ignored if present in a de-serialized JSON.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    If None, will retain whatever configuration is currently applied. Defaults to None

  • supports_yaml (bool / tuple of form (inbound: bool, outbound: bool) / None) –

    Determines whether the column can be serialized to or de-serialized from YAML format.

    If True, can be serialized to YAML and de-serialized from YAML. If False, will not be included when serialized to YAML and will be ignored if present in a de-serialized YAML.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    If None, will retain whatever configuration is currently applied. Defaults to None

  • supports_dict (bool / tuple of form (inbound: bool, outbound: bool) / None) –

    Determines whether the column can be serialized to or de-serialized to a Python dict.

    If True, can be serialized to dict and de-serialized from a dict. If False, will not be included when serialized to dict and will be ignored if present in a de-serialized dict.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    If None, will retain whatever configuration is currently applied. Defaults to None

  • on_deserialize (callable / dict with formats as keys and values as callables / None) –

    A function that will be called when attempting to assign a de-serialized value to the column. This is intended to either coerce the value being assigned to a form that is acceptable by the column, or raise an exception if it cannot be coerced.

    Tip

    If you need to execute different on_deserialize functions for different formats, you can also supply a dict:

    on_deserialize = {
      'csv': csv_on_deserialize_callable,
      'json': json_on_deserialize_callable,
      'yaml': yaml_on_deserialize_callable,
      'dict': dict_on_deserialize_callable
    }
    

    If False, will clear the current configuration to apply the default.

    If None, will retain whatever configuration is currently applied. Defaults to None

    Tip

    To clear the on_deserialize function, you can either supply a value of False or pass a dict with particular formats set to None:

    on_deserialize = {
      'csv': None,
      'json': None,
      'yaml': None,
      'dict': None
    }
    
    # is equivalent to:
    
    on_deserialize = False
    

    This will revert the on_deserialize function to the attribute’s default on_deserialize function based on its data type.

  • on_serialize (callable / dict with formats as keys and values as callables / None / False) –

    A function that will be called when attempting to serialize a value from the column.

    Tip

    If you need to execute different on_serialize functions for different formats, you can also supply a dict:

    on_serialize = {
      'csv': csv_on_serialize_callable,
      'json': json_on_serialize_callable,
      'yaml': yaml_on_serialize_callable,
      'dict': dict_on_serialize_callable
    }
    

    If False, will clear the current configuration to apply the default configuration.

    If None, will retain whatever configuration is currently applied. Defaults to None

    Tip

    To clear the on_serialize function, you need to pass False or a dict with particular formats set to None:

    on_serialize = {
      'csv': None,
      'json': None,
      'yaml': None,
      'dict': None
    }
    
    # is equivalent to
    
    on_serialize = False
    

    This will revert the on_serialize function to the attribute’s default on_serialize function based on its data type.

  • csv_sequence (int / None / False) –

    Indicates the numbered position that the column should be in in a valid CSV-version of the object.

    Note

    If not specified, the column will go after any columns that do have a csv_sequence assigned, sorted alphabetically.

    If two columns have the same csv_sequence, they will be sorted alphabetically.

    If False, will set the position to None <python:None>` which will position the column after any explicitly positioned columns in alphabetical order.

    If None, will retain whatever configuration is currently applied. Defaults to None

Raises:
  • ConfigurationError – if config_set is not empty and there are no configuration sets defined on cls or if there are configuration sets defined but no config_set is specified
  • ValueError – if config_set is not defined within __serialization__
  • ValueError – if attribute does not match config.name if config is not None
to_csv(include_header=False, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', config_set=None)

Retrieve a CSV string with the object’s data.

Parameters:
  • include_header (bool) – If True, will include a header row with column labels. If False, will not include a header row. Defaults to True.
  • delimiter (str) – The delimiter used between columns. Defaults to |.
  • wrap_all_strings (bool) – If True, wraps any string data in the wrapper_character. If None, only wraps string data if it contains the delimiter. Defaults to False.
  • null_text (str) – The text value to use in place of empty values. Only applies if wrap_empty_values is True. Defaults to 'None'.
  • wrapper_character (str) – The string used to wrap string values when wrapping is necessary. Defaults to '.
  • double_wrapper_character_when_nested (bool) – If True, will double the wrapper_character when it is found inside a column value. If False, will precede the wrapper_character by the escape_character when it is found inside a column value. Defaults to False.
  • escape_character (str) – The character to use when escaping nested wrapper characters. Defaults to \.
  • line_terminator (str) – The character used to mark the end of a line. Defaults to \r\n.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Returns:

Data from the object in CSV format ending in a newline (\n).

Return type:

str

to_dict(max_nesting=0, current_nesting=0, config_set=None)

Return a OrderedDict representation of the object.

Parameters:
  • max_nesting (int) – The maximum number of levels that the resulting dict object can be nested. If set to 0, will not nest other serializable objects. Defaults to 0.
  • current_nesting (int) – The current nesting level at which the dict representation will reside. Defaults to 0.
  • config_set (str / None) – If not None, the named configuration set to use when processing the input. Defaults to None.
Returns:

A OrderedDict representation of the object.

Return type:

OrderedDict

Raises:
to_json(max_nesting=0, current_nesting=0, serialize_function=None, config_set=None, **kwargs)

Return a JSON representation of the object.

Parameters:
  • max_nesting (int) – The maximum number of levels that the resulting JSON object can be nested. If set to 0, will not nest other serializable objects. Defaults to 0.
  • current_nesting (int) – The current nesting level at which the dict representation will reside. Defaults to 0.
  • serialize_function (callable / None) –

    Optionally override the default JSON serializer. Defaults to None, which applies the default simplejson JSON serializer.

    Note

    Use the serialize_function parameter to override the default JSON serializer.

    A valid serialize_function is expected to accept a single dict and return a str, similar to simplejson.dumps().

    If you wish to pass additional arguments to your serialize_function pass them as keyword arguments (in kwargs).

  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
  • kwargs (keyword arguments) – Optional keyword parameters that are passed to the JSON serializer function. By default, these are options which are passed to simplejson.dumps().
Returns:

A str with the JSON representation of the object.

Return type:

str

Raises:
to_yaml(max_nesting=0, current_nesting=0, serialize_function=None, config_set=None, **kwargs)

Return a YAML representation of the object.

Parameters:
  • max_nesting (int) – The maximum number of levels that the resulting object can be nested. If set to 0, will not nest other serializable objects. Defaults to 0.
  • current_nesting (int) – The current nesting level at which the representation will reside. Defaults to 0.
  • serialize_function (callable / None) –

    Optionally override the default YAML serializer. Defaults to None, which calls the default yaml.dump() function from the PyYAML library.

    Note

    Use the serialize_function parameter to override the default YAML serializer.

    A valid serialize_function is expected to accept a single dict and return a str, similar to yaml.dump().

    If you wish to pass additional arguments to your serialize_function pass them as keyword arguments (in kwargs).

  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
  • kwargs (keyword arguments) – Optional keyword parameters that are passed to the YAML serializer function. By default, these are options which are passed to yaml.dump().
Returns:

A str with the JSON representation of the object.

Return type:

str

Raises:
update_from_csv(csv_data, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', config_set=None)

Update the model instance from a CSV record.

Tip

Unwrapped empty column values are automatically interpreted as null (None).

Parameters:
  • csv_data (str / Path-like object) – The CSV data. If a Path-like object, will read the first record from a file that is assumed to include a header row. If a str and has more than one record (line), will assume the first line is a header row.
  • delimiter (str) – The delimiter used between columns. Defaults to |.
  • wrapper_character (str) – The string used to wrap string values when wrapping is applied. Defaults to '.
  • null_text (str) – The string used to indicate an empty value if empty values are wrapped. Defaults to None.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
Raises:
update_from_dict(input_data, error_on_extra_keys=True, drop_extra_keys=False, config_set=None)

Update the model instance from data in a dict object.

Parameters:
  • input_data (dict) – The input dict
  • error_on_extra_keys (bool) –

    If True, will raise an error if an unrecognized key is found in input_data. If False, will either drop or include the extra key in the result, as configured in the drop_extra_keys parameter. Defaults to True.

    Warning

    Be careful setting error_on_extra_keys to False.

    This method’s last step attempts to set an attribute on the model instance for every top-level key in the parsed/processed input data.

    If there is an extra key that cannot be set as an attribute on your model instance, it will raise AttributeError.

  • drop_extra_keys (bool) – If True, will omit unrecognized top-level keys from the resulting dict. If False, will include unrecognized keys or raise an error based on the configuration of the error_on_extra_keys parameter. Defaults to False.
  • config_set (str / None) – If not None, the named configuration set to use when processing the input. Defaults to None.
Raises:
  • ExtraKeyError – if error_on_extra_keys is True and input_data contains top-level keys that are not recognized as attributes for the instance model.
  • DeserializationError – if input_data is not a dict or JSON object serializable to a dict or if input_data is empty.
update_from_json(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)

Update the model instance from data in a JSON string.

Parameters:
  • input_data (str or Path-like object) –

    The JSON data to de-serialize.

    Note

    If input_data points to a file, and the file contains a list of JSON objects, the first JSON object will be considered.

  • deserialize_function (callable / None) –

    Optionally override the default JSON deserializer. Defaults to None, which calls the default simplejson.loads() function from the simplejson library.

    Note

    Use the deserialize_function parameter to override the default JSON deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to simplejson.loads().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in kwargs).

  • error_on_extra_keys (bool) –

    If True, will raise an error if an unrecognized key is found in input_data. If False, will either drop or include the extra key in the result, as configured in the drop_extra_keys parameter. Defaults to True.

    Warning

    Be careful setting error_on_extra_keys to False.

    This method’s last step attempts to set an attribute on the model instance for every top-level key in the parsed/processed input data.

    If there is an extra key that cannot be set as an attribute on your model instance, it will raise AttributeError.

  • drop_extra_keys (bool) – If True, will ignore unrecognized keys in the input data. If False, will include unrecognized keys or raise an error based on the configuration of the error_on_extra_keys parameter. Defaults to False.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
  • kwargs (keyword arguments) – Optional keyword parameters that are passed to the JSON deserializer function.By default, these are options which are passed to simplejson.loads().
Raises:
  • ExtraKeyError – if error_on_extra_keys is True and input_data contains top-level keys that are not recognized as attributes for the instance model.
  • DeserializationError – if input_data is not a str JSON de-serializable object to a dict or if input_data is empty.
update_from_yaml(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)

Update the model instance from data in a YAML string.

Parameters:
  • input_data (str / Path-like object) – The YAML data to de-serialize. May be either a str or a Path-like object to a YAML file.
  • deserialize_function (callable / None) –

    Optionally override the default YAML deserializer. Defaults to None, which calls the default yaml.safe_load() function from the PyYAML library.

    Note

    Use the deserialize_function parameter to override the default YAML deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to yaml.safe_load().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in kwargs).

  • error_on_extra_keys (bool) –

    If True, will raise an error if an unrecognized key is found in input_data. If False, will either drop or include the extra key in the result, as configured in the drop_extra_keys parameter. Defaults to True.

    Warning

    Be careful setting error_on_extra_keys to False.

    This method’s last step attempts to set an attribute on the model instance for every top-level key in the parsed/processed input data.

    If there is an extra key that cannot be set as an attribute on your model instance, it will raise AttributeError.

  • drop_extra_keys (bool) – If True, will ignore unrecognized keys in the input data. If False, will include unrecognized keys or raise an error based on the configuration of the error_on_extra_keys parameter. Defaults to False.
  • config_set (str / None) – If not None, the named configuration set to use. Defaults to None.
  • kwargs (keyword arguments) – Optional keyword parameters that are passed to the YAML deserializer function. By default, these are options which are passed to yaml.safe_load().
Raises:
  • ExtraKeyError – if error_on_extra_keys is True and input_data contains top-level keys that are not recognized as attributes for the instance model.
  • DeserializationError – if input_data is not a str YAML de-serializable object to a dict or if input_data is empty.
primary_key_value

The instance’s primary key.

Note

If not None, this value can always be passed to Query.get().

Warning

Returns None if the instance is pending, in a transient state, or does not have a primary key.

Returns:scalar or tuple value representing the primary key. For a composite primary key, the order of identifiers corresponds to the order with which the model’s primary keys were defined. If no primary keys are available, will return None.
Return type:scalar / tuple / None

declarative_base()

declarative_base(cls=<class 'sqlathanor.declarative.base_model.BaseModel'>, **kwargs)[source]

Construct a base class for declarative class definitions.

The new base class will be given a metaclass that produces appropriate Table objects and makes the appropriate mapper calls based on the information provided declaratively in the class and any subclasses of the class.

Parameters:
  • cls (None / tuple of classes / class object) –

    Defaults to BaseModel to provide serialization/de-serialization support.

    If a tuple of classes, will include BaseModel in that list of classes to mixin serialization/de-serialization support.

    If not None and not a tuple, will mixin BaseModel with the value passed to provide serialization/de-serialization support.

  • kwargs (keyword arguments) – Additional keyword arguments supported by the original sqlalchemy.ext.declarative.declarative_base() function
Returns:

Base class for declarative class definitions with support for serialization and de-serialization.


@as_declarative

as_declarative(**kw)[source]

Class decorator for declarative_base().

Provides a syntactical shortcut to the cls argument sent to declarative_base(), allowing the base class to be converted in-place to a “declarative” base:

from sqlathanor import as_declarative

@as_declarative()
class Base(object):
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    id = Column(Integer,
                primary_key = True,
                supports_csv = True)

class MyMappedClass(Base):
    # ...

Tip

All keyword arguments passed to as_declarative() are passed along to declarative_base().


generate_model_from_csv()

generate_model_from_csv(serialized, tablename, primary_key, cls=<class 'sqlathanor.declarative.base_model.BaseModel'>, serialization_config=None, skip_nested=True, default_to_str=False, type_mapping=None, base_model_attrs=None, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', **kwargs)[source]

Generate a model class from a serialized CSV string.

Note

This function cannot programmatically create relationships, hybrid properties, or association proxies.

Parameters:
  • serialized (str / Path-like object / list) –

    The CSV data whose column headers will be treated as column names, while value data types will determine model attribute data types.

    Note

    If a Path-like object, will read the file contents from a file that is assumed to include a header row. If a str and has more than one record (line), will assume the first line is a header row. If a list, will assume the first item is the header row.

  • tablename (str) – The name of the SQL table to which the model corresponds.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • cls (None / tuple of classes / class object) –

    The base class to use when generating a new model class. Defaults to BaseModel to provide serialization/de-serialization support.

    If a tuple of classes, will include BaseModel in that list of classes to mixin serialization/de-serialization support.

    If not None and not a tuple, will mixin BaseModel with the value passed to provide serialization/de-serialization support.

  • serialization_config (Iterable of AttributeConfiguration or coercable dict objects / None) – Collection of AttributeConfiguration that determine the generated model’s serialization/de-serialization configuration. If None, will support serialization and de-serialization across all keys in serialized_dict. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized_json that feature nested items (e.g. iterables, JSON objects, etc.) will be ignored. If False, will treat serialized items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • base_model_attrs (dict / None) – Optional dict of special attributes that will be applied to the generated BaseModel (e.g. __table_args__). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults to None.
  • delimiter (str) – The delimiter used between columns. Defaults to |.
  • wrapper_character (str) – The string used to wrap string values when wrapping is applied. Defaults to '.
  • null_text (str) – The string used to indicate an empty value if empty values are wrapped. Defaults to None.
  • kwargs – Any additional keyword arguments will be passed to declarative_base() when generating the programmatic BaseModel.
Returns:

Model class whose structure matches serialized.

Return type:

BaseModel

Raises:

generate_model_from_json()

generate_model_from_json(serialized, tablename, primary_key, deserialize_function=None, cls=<class 'sqlathanor.declarative.base_model.BaseModel'>, serialization_config=None, skip_nested=True, default_to_str=False, type_mapping=None, base_model_attrs=None, deserialize_kwargs=None, **kwargs)[source]

Generate a model class from a serialized JSON string.

Note

This function cannot programmatically create relationships, hybrid properties, or association proxies.

Parameters:
  • serialized (str / Path-like object) –

    The JSON data whose keys will be treated as column names, while value data types will determine model attribute data types, or the path to a file whose contents will be the JSON object in question.

    Note

    If providing a path to a file, and if the file contains more than one JSON object, will only use the first JSON object listed.

  • tablename (str) – The name of the SQL table to which the model corresponds.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • deserialize_function (callable / None) –

    Optionally override the default JSON deserializer. Defaults to None, which calls the default simplejson.loads() function from the doc:simplejson <simplejson:index> library.

    Note

    Use the deserialize_function parameter to override the default JSON deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to simplejson.loads().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in deserialize_kwargs).

  • cls (None / tuple of classes / class object) –

    The base class to use when generating a new model class. Defaults to BaseModel to provide serialization/de-serialization support.

    If a tuple of classes, will include BaseModel in that list of classes to mixin serialization/de-serialization support.

    If not None and not a tuple, will mixin BaseModel with the value passed to provide serialization/de-serialization support.

  • serialization_config (Iterable of AttributeConfiguration or coercable dict objects / None) – Collection of AttributeConfiguration that determine the generated model’s serialization/de-serialization configuration. If None, will support serialization and de-serialization across all keys in serialized_dict. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized_json that feature nested items (e.g. iterables, JSON objects, etc.) will be ignored. If False, will treat serialized items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • base_model_attrs (dict / None) – Optional dict of special attributes that will be applied to the generated BaseModel (e.g. __table_args__). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults to None.
  • deserialize_kwargs (dict / None) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults to None.
  • kwargs – Any additional keyword arguments will be passed to declarative_base() when generating the programmatic BaseModel.
Returns:

Model class whose structure matches serialized.

Return type:

BaseModel

Raises:

generate_model_from_yaml()

generate_model_from_yaml(serialized, tablename, primary_key, deserialize_function=None, cls=<class 'sqlathanor.declarative.base_model.BaseModel'>, serialization_config=None, skip_nested=True, default_to_str=False, type_mapping=None, base_model_attrs=None, deserialize_kwargs=None, **kwargs)[source]

Generate a model class from a serialized YAML string.

Note

This function cannot programmatically create relationships, hybrid properties, or association proxies.

Parameters:
  • serialized (str / Path-like object) – The YAML data whose keys will be treated as column names, while value data types will determine model attribute data types, or the path to a file whose contents will be the YAML object in question.
  • tablename (str) – The name of the SQL table to which the model corresponds.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • deserialize_function (callable / None) –

    Optionally override the default YAML deserializer. Defaults to None, which calls the default yaml.safe_load() function from the PyYAML library.

    Note

    Use the deserialize_function parameter to override the default YAML deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to yaml.safe_load().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in kwargs).

  • cls (None / tuple of classes / class object) –

    The base class to use when generating a new model class. Defaults to BaseModel to provide serialization/de-serialization support.

    If a tuple of classes, will include BaseModel in that list of classes to mixin serialization/de-serialization support.

    If not None and not a tuple, will mixin BaseModel with the value passed to provide serialization/de-serialization support.

  • serialization_config (Iterable of AttributeConfiguration or coercable dict objects / None) – Collection of AttributeConfiguration that determine the generated model’s serialization/de-serialization configuration. If None, will support serialization and de-serialization across all keys in serialized_dict. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized_json that feature nested items (e.g. iterables, JSON objects, etc.) will be ignored. If False, will treat serialized items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • base_model_attrs (dict / None) – Optional dict of special attributes that will be applied to the generated BaseModel (e.g. __table_args__). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults to None.
  • deserialize_kwargs (dict / None) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults to None.
  • kwargs – Any additional keyword arguments will be passed to declarative_base() when generating the programmatic BaseModel.
Returns:

Model class whose structure matches serialized.

Return type:

BaseModel

Raises:

generate_model_from_dict()

generate_model_from_dict(serialized_dict, tablename, primary_key, cls=<class 'sqlathanor.declarative.base_model.BaseModel'>, serialization_config=None, skip_nested=True, default_to_str=False, type_mapping=None, base_model_attrs=None, **kwargs)[source]

Generate a model class from a serialized dict.

Note

This function cannot programmatically create relationships, hybrid properties, or association proxies.

Parameters:
  • serialized_dict (dict) – The dict that has been de-serialized from a given string. Keys will be treated as column names, while value data types will determine model attribute data types.
  • tablename (str) – The name of the SQL table to which the model corresponds.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • cls (None / tuple of classes / class object) –

    The base class to use when generating a new model class. Defaults to BaseModel to provide serialization/de-serialization support.

    If a tuple of classes, will include BaseModel in that list of classes to mixin serialization/de-serialization support.

    If not None and not a tuple, will mixin BaseModel with the value passed to provide serialization/de-serialization support.

  • serialization_config (Iterable of AttributeConfiguration or coercable dict objects / None) – Collection of AttributeConfiguration that determine the generated model’s serialization/de-serialization configuration. If None, will support serialization and de-serialization across all keys in serialized_dict. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized_dict that feature nested items (e.g. iterables, dict objects, etc.) will be ignored. If False, will treat serialized items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized_dict map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • base_model_attrs (dict / None) – Optional dict of special attributes that will be applied to the generated BaseModel (e.g. __table_args__). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults to None.
  • kwargs – Any additional keyword arguments will be passed to declarative_base() when generating the programmatic BaseModel.
Returns:

Model class whose structure matches serialized_dict.

Return type:

BaseModel

Raises:

Schema

The classes defined in sqlathanor.schema are drop-in replacements for SQLAlchemy’s Core Schema elements.

They add serialization and de-serialization support to your model’s columns and relationsips, and so should replace your imports of their SQLAlchemy analogs.

See also

Column

class Column(*args, **kwargs)[source]

Represents a column in a database table. Inherits from sqlalchemy.schema.Column

__init__(*args, **kwargs)[source]

Construct a new Column object.

Warning

This method is analogous to the original SQLAlchemy Column.__init__() from which it inherits. The only difference is that it supports additional keyword arguments which are not supported in the original, and which are documented below.

For the original SQLAlchemy version, see:

Parameters:
  • supports_csv (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from CSV format.

    If True, can be serialized to CSV and de-serialized from CSV. If False, will not be included when serialized to CSV and will be ignored if present in a de-serialized CSV.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to CSV or de-serialized from CSV.

  • csv_sequence (int / None) –

    Indicates the numbered position that the column should be in in a valid CSV-version of the object. Defaults to None.

    Note

    If not specified, the column will go after any columns that do have a csv_sequence assigned, sorted alphabetically.

    If two columns have the same csv_sequence, they will be sorted alphabetically.

  • supports_json (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from JSON format.

    If True, can be serialized to JSON and de-serialized from JSON. If False, will not be included when serialized to JSON and will be ignored if present in a de-serialized JSON.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to JSON or de-serialized from JSON.

  • supports_yaml (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from YAML format.

    If True, can be serialized to YAML and de-serialized from YAML. If False, will not be included when serialized to YAML and will be ignored if present in a de-serialized YAML.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to YAML or de-serialized from YAML.

  • supports_dict (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized to a Python dict.

    If True, can be serialized to dict and de-serialized from a dict. If False, will not be included when serialized to dict and will be ignored if present in a de-serialized dict.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to a dict or de-serialized from a dict.

  • on_deserialize (callable / dict with formats as keys and values as callables) –

    A function that will be called when attempting to assign a de-serialized value to the column. This is intended to either coerce the value being assigned to a form that is acceptable by the column, or raise an exception if it cannot be coerced. If None, the data type’s default on_deserialize function will be called instead.

    Tip

    If you need to execute different on_deserialize functions for different formats, you can also supply a dict:

    on_deserialize = {
      'csv': csv_on_deserialize_callable,
      'json': json_on_deserialize_callable,
      'yaml': yaml_on_deserialize_callable,
      'dict': dict_on_deserialize_callable
    }
    

    Defaults to None.

  • on_serialize (callable / dict with formats as keys and values as callables) –

    A function that will be called when attempting to serialize a value from the column. If None, the data type’s default on_serialize function will be called instead.

    Tip

    If you need to execute different on_serialize functions for different formats, you can also supply a dict:

    on_serialize = {
      'csv': csv_on_serialize_callable,
      'json': json_on_serialize_callable,
      'yaml': yaml_on_serialize_callable,
      'dict': dict_on_serialize_callable
    }
    

    Defaults to None.


relationship()

relationship(argument, supports_json = False, supports_yaml = False, supports_dict = False, **kwargs)

Provide a relationship between two mapped classes.

Warning

This constructor is analogous to the original SQLAlchemy relationship() from which it inherits. The only difference is that it supports additional keyword arguments which are not supported in the original, and which are documented below.

For the original SQLAlchemy version, see: sqlalchemy.orm.relationship()

Parameters:
  • argument – see sqlalchemy.orm.relationship()
  • supports_json (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from JSON format.

    If True, can be serialized to JSON and de-serialized from JSON. If False, will not be included when serialized to JSON and will be ignored if present in a de-serialized JSON.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to JSON or de-serialized from JSON.

  • supports_yaml (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from YAML format.

    If True, can be serialized to YAML and de-serialized from YAML. If False, will not be included when serialized to YAML and will be ignored if present in a de-serialized YAML.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to YAML or de-serialized from YAML.

  • supports_dict (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized to a Python dict.

    If True, can be serialized to dict and de-serialized from a dict. If False, will not be included when serialized to dict and will be ignored if present in a de-serialized dict.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to a dict or de-serialized from a dict.


Table

class Table(*args, **kwargs)[source]

Represents a table in a database. Inherits from sqlalchemy.schema.Table

__init__(*args, **kwargs)[source]

Construct a new Table object.

Warning

This method is analogous to the original SQLAlchemy Table.__init__() from which it inherits. The only difference is that it supports additional keyword arguments which are not supported in the original, and which are documented below.

For the original SQLAlchemy version, see:

classmethod from_csv(serialized, tablename, metadata, primary_key, column_kwargs=None, skip_nested=True, default_to_str=False, type_mapping=None, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character='\\', line_terminator='\r\n', **kwargs)[source]

Generate a Table object from a CSV string.

Parameters:
  • serialized (str / Path-like object / list) –

    The CSV data whose column headers will be treated as column names, while value data types will determine model attribute data types.

    Note

    If a Path-like object, will read the file contents from a file that is assumed to include a header row. If a str and has more than one record (line), will assume the first line is a header row. If a list, will assume the first item is the header row.

  • tablename (str) – The name of the SQL table to which the model corresponds.
  • metadata (MetaData) – a MetaData object which will contain this table. The metadata is used as a point of association of this table with other tables which are referenced via foreign key. It also may be used to associate this table with a particular Connectable.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • column_kwargs (dict / None) – An optional dictionary whose keys correspond to column/key, and whose values are themselves dictionaries with keyword arguments that will be passed ot the applicable Column constructor. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized that feature nested items (e.g. iterables, dict objects, etc.) will be ignored. If False, will treat nested items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • delimiter (str) – The delimiter used between columns. Defaults to |.
  • wrapper_character (str) – The string used to wrap string values when wrapping is applied. Defaults to '.
  • null_text (str) – The string used to indicate an empty value if empty values are wrapped. Defaults to None.
  • kwargs – Any additional keyword arguments will be passed to the Table constructor. For a full list of options, please see sqlalchemy.schema.Table.
Returns:

A Table object.

Return type:

Table

Raises:
classmethod from_dict(serialized, tablename, metadata, primary_key, column_kwargs=None, skip_nested=True, default_to_str=False, type_mapping=None, **kwargs)[source]

Generate a Table object from a dict.

Parameters:
  • serialized (dict) – The dict that has been de-serialized from a given string. Keys will be treated as column names, while value data types will determine Column data types.
  • tablename (str) – The name of the SQL table to which the model corresponds.
  • metadata (MetaData) – a MetaData object which will contain this table. The metadata is used as a point of association of this table with other tables which are referenced via foreign key. It also may be used to associate this table with a particular Connectable.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • column_kwargs (dict / None) – An optional dictionary whose keys correspond to column/key, and whose values are themselves dictionaries with keyword arguments that will be passed ot the applicable Column constructor. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized that feature nested items (e.g. iterables, dict objects, etc.) will be ignored. If False, will treat nested items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • kwargs – Any additional keyword arguments will be passed to the Table constructor. For a full list of options, please see sqlalchemy.schema.Table.
Returns:

A Table object.

Return type:

Table

Raises:
classmethod from_json(serialized, tablename, metadata, primary_key, column_kwargs=None, skip_nested=True, default_to_str=False, type_mapping=None, deserialize_function=None, deserialize_kwargs=None, **kwargs)[source]

Generate a Table object from a JSON string.

Parameters:
  • serialized (str / Path-like object) –

    The JSON data to use. Keys will be treated as column names, while value data types will determine Column data types.

    Note

    If providing a path to a file, and if the file contains more than one JSON object, will only use the first JSON object listed.

  • tablename (str) – The name of the SQL table to which the model corresponds.
  • metadata (MetaData) – a MetaData object which will contain this table. The metadata is used as a point of association of this table with other tables which are referenced via foreign key. It also may be used to associate this table with a particular Connectable.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • column_kwargs (dict / None) – An optional dictionary whose keys correspond to column/key, and whose values are themselves dictionaries with keyword arguments that will be passed ot the applicable Column constructor. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized that feature nested items (e.g. iterables, dict objects, etc.) will be ignored. If False, will treat nested items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • deserialize_function (callable / None) –

    Optionally override the default JSON deserializer. Defaults to None, which calls the default simplejson.loads() function from the doc:simplejson <simplejson:index> library.

    Note

    Use the deserialize_function parameter to override the default JSON deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to simplejson.loads().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in deserialize_kwargs).

  • deserialize_kwargs (dict / None) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults to None.
  • kwargs – Any additional keyword arguments will be passed to the Table constructor. For a full list of options, please see sqlalchemy.schema.Table.
Returns:

A Table object.

Return type:

Table

Raises:
classmethod from_yaml(serialized, tablename, metadata, primary_key, column_kwargs=None, skip_nested=True, default_to_str=False, type_mapping=None, deserialize_function=None, deserialize_kwargs=None, **kwargs)[source]

Generate a Table object from a YAML string.

Parameters:
  • serialized (str / Path-like object) –

    The YAML string to use. Keys will be treated as column names, while value data types will determine Column data types.

    Note

    If providing a path to a file, and if the file contains more than one object, will only use the first object listed.

  • tablename (str) – The name of the SQL table to which the model corresponds.
  • metadata (MetaData) – a MetaData object which will contain this table. The metadata is used as a point of association of this table with other tables which are referenced via foreign key. It also may be used to associate this table with a particular Connectable.
  • primary_key (str) – The name of the column/key that should be used as the table’s primary key.
  • column_kwargs (dict / None) – An optional dictionary whose keys correspond to column/key, and whose values are themselves dictionaries with keyword arguments that will be passed ot the applicable Column constructor. Defaults to None.
  • skip_nested (bool) – If True then any keys in serialized that feature nested items (e.g. iterables, dict objects, etc.) will be ignored. If False, will treat nested items as str. Defaults to True.
  • default_to_str (bool) – If True, will automatically set a key/column whose value type cannot be determined to str (Text). If False, will use the value type’s __name__ attribute and attempt to find a mapping. Defaults to False.
  • type_mapping (dict with type names as keys and column data types as values.) –

    Determines how value types in serialized map to SQL column data types. To add a new mapping or override a default, set a key to the name of the value type in Python, and set the value to a SQLAlchemy Data Type. The following are the default mappings applied:

    Python Literal SQL Column Type
    bool Boolean
    str Text
    int Integer
    float Float
    date Date
    datetime DateTime
    time Time
  • deserialize_function (callable / None) –

    Optionally override the default YAML deserializer. Defaults to None, which calls the default yaml.safe_load() function from the PyYAML library.

    Note

    Use the deserialize_function parameter to override the default YAML deserializer.

    A valid deserialize_function is expected to accept a single str and return a dict, similar to yaml.safe_load().

    If you wish to pass additional arguments to your deserialize_function pass them as keyword arguments (in kwargs).

  • deserialize_kwargs (dict / None) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults to None.
  • kwargs – Any additional keyword arguments will be passed to the Table constructor. For a full list of options, please see sqlalchemy.schema.Table.
Returns:

A Table object.

Return type:

Table

Raises:

Attribute Configuration

The following classes and functions are used to apply meta configuration to your SQLAlchemy model.

See also

AttributeConfiguration

class AttributeConfiguration(*args, **kwargs)[source]

Serialization/de-serialization configuration of a model attribute.

__init__(*args, **kwargs)[source]

Construct an AttributeConfiguration object.

Parameters:
  • name (str) – The name of the attribute. Defaults to None.
  • supports_csv (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from CSV format.

    If True, can be serialized to CSV and de-serialized from CSV. If False, will not be included when serialized to CSV and will be ignored if present in a de-serialized CSV.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to CSV or de-serialized from CSV.

  • supports_json (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from JSON format.

    If True, can be serialized to JSON and de-serialized from JSON. If False, will not be included when serialized to JSON and will be ignored if present in a de-serialized JSON.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to JSON or de-serialized from JSON.

  • supports_yaml (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized from YAML format.

    If True, can be serialized to YAML and de-serialized from YAML. If False, will not be included when serialized to YAML and will be ignored if present in a de-serialized YAML.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to YAML or de-serialized from YAML.

  • supports_dict (bool / tuple of form (inbound: bool, outbound: bool)) –

    Determines whether the column can be serialized to or de-serialized to a Python dict.

    If True, can be serialized to dict and de-serialized from a dict. If False, will not be included when serialized to dict and will be ignored if present in a de-serialized dict.

    Can also accept a 2-member tuple (inbound / outbound) which determines de-serialization and serialization support respectively.

    Defaults to False, which means the column will not be serialized to a dict or de-serialized from a dict.

  • on_deserialize (callable / dict with formats as keys and values as callables) –

    A function that will be called when attempting to assign a de-serialized value to the column. This is intended to either coerce the value being assigned to a form that is acceptable by the column, or raise an exception if it cannot be coerced. If None, the data type’s default on_deserialize function will be called instead.

    Tip

    If you need to execute different on_deserialize functions for different formats, you can also supply a dict:

    on_deserialize = {
      'csv': csv_on_deserialize_callable,
      'json': json_on_deserialize_callable,
      'yaml': yaml_on_deserialize_callable,
      'dict': dict_on_deserialize_callable
    }
    

    Defaults to None.

  • on_serialize (callable / dict with formats as keys and values as callables) –

    A function that will be called when attempting to serialize a value from the column. If None, the data type’s default on_serialize function will be called instead.

    Tip

    If you need to execute different on_serialize functions for different formats, you can also supply a dict:

    on_serialize = {
      'csv': csv_on_serialize_callable,
      'json': json_on_serialize_callable,
      'yaml': yaml_on_serialize_callable,
      'dict': dict_on_serialize_callable
    }
    

    Defaults to None.

  • csv_sequence (int / None) –

    Indicates the numbered position that the column should be in in a valid CSV-version of the object. Defaults to None.

    Note

    If not specified, the column will go after any columns that do have a csv_sequence assigned, sorted alphabetically.

    If two columns have the same csv_sequence, they will be sorted alphabetically.

  • attribute (class attribute) – The object representation of an attribute. Supplying this value overrides any other configuration options supplied. Defaults to None.
  • display_name (str / None) – An optional name to use or expect in place of name when serializing or de-serializing the attribute. If None, the attribute will default to the same name as in its Python model class and as provided in name. Defaults to None
classmethod from_attribute(attribute)[source]

Return an instance of AttributeConfiguration configured for a given attribute.

classmethod fromkeys(seq, value=None)[source]

Create a new AttributeConfiguration with keys in seq and values in value.

Parameters:
  • seq (iterable) – Iterable of keys
  • value (iterable) – Iterable of values
Return type:

AttributeConfiguration

csv_sequence

Column position when serialized to or de-serialized from CSV.

Note

If None, will default to alphabetical sorting after any attributes that have an explicit csv_sequence provided.

Return type:int / None.
display_name

The property name to apply when serializing the attribute or to expect when de-serializing.

Note

If None, will default to the attribute name in the Python model class.

Return type:str / None.
name

The name of the attribute.

Return type:str / None
on_deserialize

A function that will be called when attempting to assign a de-serialized value to the attribute.

This is intended to either coerce the value being assigned to a form that is acceptable by the attribute, or raise an exception if it cannot be coerced.

If None, the data type’s default on_deserialize function will be called instead.

Tip

If you need to execute different on_deserialize functions for different formats, you can also supply a dict:

on_deserialize = {
    'csv': csv_on_deserialize_callable,
    'json': json_on_deserialize_callable,
    'yaml': yaml_on_deserialize_callable,
    'dict': dict_on_deserialize_callable
}

Defaults to None.

Return type:callable / dict with formats as keys and values as callables
on_serialize

A function that will be called when attempting to serialize a value from the attribute.

If None, the data type’s default on_serialize function will be called instead.

Tip

If you need to execute different on_serialize functions for different formats, you can also supply a dict:

on_serialize = {
    'csv': csv_on_serialize_callable,
    'json': json_on_serialize_callable,
    'yaml': yaml_on_serialize_callable,
    'dict': dict_on_serialize_callable
}

Defaults to None.

Return type:callable / dict with formats as keys and values as callables
supports_csv

Indicates whether the attribute can be serialized / de-serialized to CSV.

Returns:2-member tuple (inbound de-serialization / outbound serialization)
Return type:tuple of form (bool, bool)
supports_dict

Indicates whether the attribute can be serialized / de-serialized to dict.

Returns:2-member tuple (inbound de-serialization / outbound serialization)
Return type:tuple of form (bool, bool)
supports_json

Indicates whether the attribute can be serialized / de-serialized to JSON.

Returns:2-member tuple (inbound de-serialization / outbound serialization)
Return type:tuple of form (bool, bool)
supports_yaml

Indicates whether the attribute can be serialized / de-serialized to YAML.

Returns:2-member tuple (inbound de-serialization / outbound serialization)
Return type:tuple of form (bool, bool)

validate_serialization_config()

validate_serialization_config(config)[source]

Validate that config contains AttributeConfiguration objects.

Parameters:config (iterable of AttributeConfiguration objects / iterable of dict objects corresponding to a AttributeConfiguration / AttributeConfiguration / dict object corresponding to a AttributeConfiguration) – Object or iterable of objects that represent AttributeConfigurations
Return type:list of AttributeConfiguration objects

Flask-SQLAlchemy / Flask-SQLAthanor

initialize_flask_sqlathanor()

initialize_flask_sqlathanor(db)[source]

Initialize SQLAthanor contents on a Flask-SQLAlchemy instance.

Parameters:

db (flask_sqlalchemy.SQLAlchemy) – The flask_sqlalchemy.SQLAlchemy instance.

Returns:

A mutated instance of db that replaces SQLAlchemy components and their Flask-SQLAlchemy flavors with SQLAthanor analogs while maintaining Flask-SQLAlchemy and SQLAlchemy functionality and interfaces.

Return type:

flask_sqlalchemy.SQLAlchemy

Raises:

FlaskBaseModel

class FlaskBaseModel[source]

Base class that establishes shared methods, attributes, and properties.

Designed to be supplied as a model_class when initializing Flask-SQLAlchemy.

See also

For detailed explanation of functionality, please see BaseModel.


Automap

automap_base(declarative_base=None, **kwargs)[source]

Produce a declarative automap base.

This function produces a new base class that is a product of the AutomapBase class as well as a declarative base that you supply.

If no declarative base is supplied, then the SQLAthanor default BaseModel will be used, to provide serialization/de-serialization support to the resulting automapped base class.

Parameters:
Returns:

A AutomapBase that can reflect your database schema structure with auto-generated declarative models that support SQLAthanor serialization/de-serialization.

Return type:

AutomapBase

Raises:

SQLAlchemySupportError – if called in an environment where SQLAlchemy is installed with a version less than 0.9.1 (which introduces automap support).


SQLAthanor Internals

RelationshipProperty

class RelationshipProperty(argument, supports_json=False, supports_yaml=False, supports_dict=False, on_serialize=None, on_deserialize=None, display_name=None, **kwargs)[source]

Describes an object property that holds a single item or list of items that correspond to a related database table.

Public constructor is the sqlathanor.schema.relationship() function.