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)¶ 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
andattributes
, the configuration inconfigs
will apply.Parameters: - configs (iterable of
AttributeConfiguration
/None
) – Collection ofAttributeConfiguration
objects to apply to the class. Defaults toNone
. - attributes (iterable of
str
/None
) – Collection of model attribute names to which a configuration will be applied. Defaults toNone
. - 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. IfFalse
, 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. IfFalse
, 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. IfFalse
, 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 todict
and de-serialized from adict
. IfFalse
, will not be included when serialized todict
and will be ignored if present in a de-serializeddict
.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 adict
: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 toNone
Tip
To clear the
on_deserialize
function, you can either supply a value ofFalse
or pass adict
with particular formats set toNone
: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 adict
: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 toNone
Tip
To clear the
on_serialize
function, you need to passFalse
or adict
with particular formats set toNone
: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.
- configs (iterable of
-
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)¶ Indicate whether
attribute
supports serialization/deserializtion.Parameters: - attribute (
str
) – The name of the attribute whose serialization support should be confirmed. - from_csv (
bool
/None
) – IfTrue
, includes attribute names that can be de-serialized from CSV strings. IfFalse
, includes attribute names that cannot be de-serialized from CSV strings. IfNone
, will not include attributes based on CSV de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_csv (
bool
/None
) – IfTrue
, includes attribute names that can be serialized to CSV strings. IfFalse
, includes attribute names that cannot be serialized to CSV strings. IfNone
, will not include attributes based on CSV serialization support (but may include them based on other parameters). Defaults toNone
. - from_json (
bool
/None
) – IfTrue
, includes attribute names that can be de-serialized from JSON strings. IfFalse
, includes attribute names that cannot be de-serialized from JSON strings. IfNone
, will not include attributes based on JSON de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_json (
bool
/None
) – IfTrue
, includes attribute names that can be serialized to JSON strings. IfFalse
, includes attribute names that cannot be serialized to JSON strings. IfNone
, will not include attributes based on JSON serialization support (but may include them based on other parameters). Defaults toNone
. - from_yaml (
bool
/None
) – IfTrue
, includes attribute names that can be de-serialized from YAML strings. IfFalse
, includes attribute names that cannot be de-serialized from YAML strings. IfNone
, will not include attributes based on YAML de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_yaml (
bool
/None
) – IfTrue
, includes attribute names that can be serialized to YAML strings. IfFalse
, includes attribute names that cannot be serialized to YAML strings. IfNone
, will not include attributes based on YAML serialization support (but may include them based on other parameters). Defaults toNone
. - from_dict (
bool
/None
) – IfTrue
, includes attribute names that can be de-serialized fromdict
objects. IfFalse
, includes attribute names that cannot be de-serialized fromdict
objects. IfNone
, will not include attributes based ondict
de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_dict – If
True
, includes attribute names that can be serialized todict
objects. IfFalse
, includes attribute names that cannot be serialized todict
objects. IfNone
, will not include attributes based ondict
serialization support (but may include them based on other parameters). Defaults toNone
.
Returns: True
if the attribute’s serialization support matches,False
if not, andNone
if no serialization support was specified.Return type: Raises: UnsupportedSerializationError – if
attribute
is not present on the object- attribute (
-
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')¶ 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.
Parameters: - include_header (
bool
) – IfTrue
, will include a header row with column labels. IfFalse
, will not include a header row. Defaults toTrue
. - delimiter (
str
) – The delimiter used between columns. Defaults to|
. - wrap_all_strings (
bool
) – IfTrue
, wraps any string data in thewrapper_character
. IfNone
, only wraps string data if it contains thedelimiter
. Defaults toFalse
. - null_text (
str
) – The text value to use in place of empty values. Only applies ifwrap_empty_values
isTrue
. 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
) – IfTrue
, will double thewrapper_character
when it is found inside a column value. IfFalse
, will precede thewrapper_character
by theescape_character
when it is found inside a column value. Defaults toFalse
. - 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
.
Returns: Data from the object in CSV format ending in a newline (
\n
).Return type: - include_header (
-
dump_to_dict
(max_nesting=0, current_nesting=0)¶ Return a
dict
representation of the object, with all attributes regardless of configuration.Caution
Nested objects (such as relationships or association proxies) will not be serialized.
Parameters: Returns: A
dict
representation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nesting
is greater thanmax_nesting
- MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
-
dump_to_json
(max_nesting=0, current_nesting=0, serialize_function=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 to0
, will not nest other serializable objects. Defaults to0
. - current_nesting (
int
) – The current nesting level at which thedict
representation will reside. Defaults to0
. - 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 singledict
and return astr
, similar tosimplejson.dumps()
.If you wish to pass additional arguments to your
serialize_function
pass them as keyword arguments (inkwargs
). - 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: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nesting
is greater thanmax_nesting
- MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
- max_nesting (
-
dump_to_yaml
(max_nesting=0, current_nesting=0, serialize_function=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 to0
, will not nest other serializable objects. Defaults to0
. - current_nesting (
int
) – The current nesting level at which the representation will reside. Defaults to0
. - serialize_function (callable /
None
) –Optionally override the default YAML serializer. Defaults to
None
, which calls the defaultyaml.dump()
function from the PyYAML library. - 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: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nesting
is greater thanmax_nesting
- MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
- max_nesting (
-
classmethod
get_attribute_serialization_config
(attribute)¶ Retrieve the
AttributeConfiguration
forattribute
.Parameters: attribute ( str
) – The attribute/column name whose serialization configuration should be returned.Returns: The AttributeConfiguration
forattribute
.Return type: AttributeConfiguration
-
classmethod
get_csv_column_names
(deserialize=True, serialize=True)¶ Retrieve a list of CSV column names.
Parameters: - deserialize (
bool
) – IfTrue
, returns columns that support de-serialization. IfFalse
, returns columns that do not support deserialization. IfNone
, does not take deserialization into account. Defaults toTrue
. - serialize (
bool
) – IfTrue
, returns columns that support serialization. IfFalse
, returns columns that do not support serialization. IfNone
, does not take serialization into account. Defaults toTrue
.
Returns: List of CSV column names, sorted according to their configuration.
Return type: - deserialize (
-
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')¶ Return the CSV representation of the model instance (record).
Parameters: - delimiter (
str
) – The delimiter used between columns. Defaults to|
. - wrap_all_strings (
bool
) – IfTrue
, wraps any string data in thewrapper_character
. IfNone
, only wraps string data if it contains thedelimiter
. Defaults toFalse
. - null_text (
str
) – The text value to use in place of empty values. Only applies ifwrap_empty_values
isTrue
. 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
) – IfTrue
, will double thewrapper_character
when it is found inside a column value. IfFalse
, will precede thewrapper_character
by theescape_character
when it is found inside a column value. Defaults toFalse
. - 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
.
Returns: Data from the object in CSV format ending in
line_terminator
.Return type: - delimiter (
-
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')¶ Retrieve a header string for a CSV representation of the model.
Parameters: - attributes (
list
ofstr
) – List of model attributes to include. - delimiter (
str
) – The character(s) to utilize between columns. Defaults to a pipe (|
). - wrap_all_strings (
bool
) – IfTrue
, wraps any string data in thewrapper_character
. IfNone
, only wraps string data if it contains thedelimiter
. Defaults toFalse
. - null_text (
str
) – The text value to use in place of empty values. Only applies ifwrap_empty_values
isTrue
. Defaults to'None'
. - null_text – The text value to use in place of empty values. Only
applies if
wrap_empty_values
isTrue
. 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
) – IfTrue
, will double thewrapper_character
when it is found inside a column value. IfFalse
, will precede thewrapper_character
by theescape_character
when it is found inside a column value. Defaults toFalse
. - 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
.
Returns: A string ending in
line_terminator
with the model’s CSV column names listed, separated by thedelimiter
.Return type: - attributes (
-
classmethod
get_csv_serialization_config
(deserialize=True, serialize=True)¶ Retrieve the CSV serialization configurations that apply for this object.
Parameters: - deserialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be de-serialized from CSV strings. IfFalse
, returns configurations for attributes that cannot be de-serialized from CSV strings. IfNone
, ignores de-serialization configuration when determining which attribute configurations to return. Defaults toNone
. - serialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be serialized to CSV strings. IfFalse
, returns configurations for attributes that cannot be serialized to CSV strings. IfNone
, ignores serialization configuration when determining which attribute configurations to return. Defaults toNone
.
Returns: Set of attribute serialization configurations that match the arguments supplied.
Return type: - deserialize (
-
classmethod
get_dict_serialization_config
(deserialize=True, serialize=True)¶ Retrieve the
dict
serialization configurations that apply for this object.Parameters: - deserialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be de-serialized fromdict
objects. IfFalse
, returns configurations for attributes that cannot be de-serialized fromdict
objects. IfNone
, ignores de-serialization configuration when determining which attribute configurations to return. Defaults toNone
. - serialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be serialized todict
objects. IfFalse
, returns configurations for attributes that cannot be serialized todict
objects. IfNone
, ignores serialization configuration when determining which attribute configurations to return. Defaults toNone
.
Returns: Set of attribute serialization configurations that match the arguments supplied.
Return type: - deserialize (
-
classmethod
get_json_serialization_config
(deserialize=True, serialize=True)¶ Retrieve the JSON serialization configurations that apply for this object.
Parameters: - deserialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be de-serialized from JSON strings. IfFalse
, returns configurations for attributes that cannot be de-serialized from JSON strings. IfNone
, ignores de-serialization configuration when determining which attribute configurations to return. Defaults toNone
. - serialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be serialized to JSON strings. IfFalse
, returns configurations for attributes that cannot be serialized to JSON strings. IfNone
, ignores serialization configuration when determining which attribute configurations to return. Defaults toNone
.
Returns: Set of attribute serialization configurations that match the arguments supplied.
Return type: - deserialize (
-
classmethod
get_primary_key_column_names
()¶ Retrieve the column names for the model’s primary key columns.
Return type: list
ofstr
-
classmethod
get_primary_key_columns
()¶ Retrieve the model’s primary key columns.
Returns: list
ofColumn
objects corresponding to the table’s primary key(s).Return type: list
ofColumn
-
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)¶ 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
) – IfTrue
, includes attribute names that can be de-serialized from CSV strings. IfFalse
, includes attribute names that cannot be de-serialized from CSV strings. IfNone
, will not include attributes based on CSV de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_csv (
bool
/None
) – IfTrue
, includes attribute names that can be serialized to CSV strings. IfFalse
, includes attribute names that cannot be serialized to CSV strings. IfNone
, will not include attributes based on CSV serialization support (but may include them based on other parameters). Defaults toNone
. - from_json (
bool
/None
) – IfTrue
, includes attribute names that can be de-serialized from JSON strings. IfFalse
, includes attribute names that cannot be de-serialized from JSON strings. IfNone
, will not include attributes based on JSON de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_json (
bool
/None
) – IfTrue
, includes attribute names that can be serialized to JSON strings. IfFalse
, includes attribute names that cannot be serialized to JSON strings. IfNone
, will not include attributes based on JSON serialization support (but may include them based on other parameters). Defaults toNone
. - from_yaml (
bool
/None
) – IfTrue
, includes attribute names that can be de-serialized from YAML strings. IfFalse
, includes attribute names that cannot be de-serialized from YAML strings. IfNone
, will not include attributes based on YAML de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_yaml (
bool
/None
) – IfTrue
, includes attribute names that can be serialized to YAML strings. IfFalse
, includes attribute names that cannot be serialized to YAML strings. IfNone
, will not include attributes based on YAML serialization support (but may include them based on other parameters). Defaults toNone
. - from_dict (
bool
/None
) – IfTrue
, includes attribute names that can be de-serialized fromdict
objects. IfFalse
, includes attribute names that cannot be de-serialized fromdict
objects. IfNone
, will not include attributes based ondict
de-serialization support (but may include them based on other parameters). Defaults toNone
. - to_dict – If
True
, includes attribute names that can be serialized todict
objects. IfFalse
, includes attribute names that cannot be serialized todict
objects. IfNone
, will not include attributes based ondict
serialization support (but may include them based on other parameters). Defaults toNone
. - exclude_private (
bool
) – IfTrue
, will exclude private attributes whose names begin with a single underscore. Defaults toTrue
.
Returns: List of attribute configurations.
Return type: - from_csv (
-
classmethod
get_yaml_serialization_config
(deserialize=True, serialize=True)¶ Retrieve the YAML serialization configurations that apply for this object.
Parameters: - deserialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be de-serialized from YAML strings. IfFalse
, returns configurations for attributes that cannot be de-serialized from YAML strings. IfNone
, ignores de-serialization configuration when determining which attribute configurations to return. Defaults toNone
. - serialize (
bool
/None
) – IfTrue
, returns configurations for attributes that can be serialized to YAML strings. IfFalse
, returns configurations for attributes that cannot be serialized to YAML strings. IfNone
, ignores serialization configuration when determining which attribute configurations to return. Defaults toNone
.
Returns: Set of attribute serialization configurations that match the arguments supplied.
Return type: - deserialize (
-
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')¶ 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 astr
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.
Returns: A model instance created from the record.
Return type: model instance
Raises: - DeserializationError – if
csv_data
is not a validstr
- CSVStructureError – if the columns in
csv_data
do not match the expected columns returned byget_csv_column_names()
- ValueDeserializationError – if a value extracted from the CSV failed when executing its de-serialization function.
- csv_data (
-
classmethod
new_from_dict
(input_data, error_on_extra_keys=True, drop_extra_keys=False)¶ Update the model instance from data in a
dict
object.Parameters: - input_data (
dict
) – The inputdict
- error_on_extra_keys (
bool
) –If
True
, will raise an error if an unrecognized key is found ininput_data
. IfFalse
, will either drop or include the extra key in the result, as configured in thedrop_extra_keys
parameter. Defaults toTrue
.Warning
Be careful setting
error_on_extra_keys
toFalse
.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 aTypeError
. - drop_extra_keys (
bool
) – IfTrue
, will omit unrecognized top-level keys from the resultingdict
. IfFalse
, will include unrecognized keys or raise an error based on the configuration of theerror_on_extra_keys
parameter. Defaults toFalse
.
Raises: - ExtraKeyError – if
error_on_extra_keys
isTrue
andinput_data
contains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_data
is not adict
or JSON object serializable to adict
or ifinput_data
is empty.
- input_data (
-
classmethod
new_from_json
(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, **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 defaultsimplejson.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 singlestr
and return adict
, similar tosimplejson.loads()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (inkwargs
). - error_on_extra_keys (
bool
) –If
True
, will raise an error if an unrecognized key is found ininput_data
. IfFalse
, will either drop or include the extra key in the result, as configured in thedrop_extra_keys
parameter. Defaults toTrue
.Warning
Be careful setting
error_on_extra_keys
toFalse
.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 aTypeError
. - drop_extra_keys (
bool
) – IfTrue
, will ignore unrecognized top-level keys ininput_data
. IfFalse
, will include unrecognized keys or raise an error based on the configuration of theerror_on_extra_keys
parameter. Defaults toFalse
. - 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
isTrue
andinput_data
contains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_data
is not adict
or JSON object serializable to adict
or ifinput_data
is empty.
- input_data (
-
classmethod
new_from_yaml
(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, **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 astr
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 defaultyaml.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 singlestr
and return adict
, similar toyaml.safe_load()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (inkwargs
). - error_on_extra_keys (
bool
) –If
True
, will raise an error if an unrecognized key is found ininput_data
. IfFalse
, will either drop or include the extra key in the result, as configured in thedrop_extra_keys
parameter. Defaults toTrue
.Warning
Be careful setting
error_on_extra_keys
toFalse
.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 aTypeError
. - drop_extra_keys (
bool
) – IfTrue
, will ignore unrecognized top-level keys ininput_data
. IfFalse
, will include unrecognized keys or raise an error based on the configuration of theerror_on_extra_keys
parameter. Defaults toFalse
.
Raises: - ExtraKeyError – if
error_on_extra_keys
isTrue
andinput_data
contains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_data
is not adict
or JSON object serializable to adict
or ifinput_data
is empty.
- input_data (
-
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)¶ Set the serialization/de-serialization configuration for
attribute
.Note
Supplying keyword arguments like
supports_csv
orsupports_json
will override any configuration set inconfig
.Parameters: - attribute (
str
) – The name of the model attribute whose serialization/de-serialization configuration is to be configured. - config (
AttributeConfiguration
/None
) – TheAttributeConfiguration
to apply. IfNone
, 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. IfFalse
, 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 toNone
- 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. IfFalse
, 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 toNone
- 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. IfFalse
, 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 toNone
- 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 todict
and de-serialized from adict
. IfFalse
, will not be included when serialized todict
and will be ignored if present in a de-serializeddict
.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 toNone
- 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 adict
: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 toNone
Tip
To clear the
on_deserialize
function, you can either supply a value ofFalse
or pass adict
with particular formats set toNone
: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 adict
: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 toNone
Tip
To clear the
on_serialize
function, you need to passFalse
or adict
with particular formats set toNone
: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 toNone
<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 toNone
Raises: ValueError – if
attribute
does not matchconfig.name
ifconfig
is notNone
- attribute (
-
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')¶ Retrieve a CSV string with the object’s data.
Parameters: - include_header (
bool
) – IfTrue
, will include a header row with column labels. IfFalse
, will not include a header row. Defaults toTrue
. - delimiter (
str
) – The delimiter used between columns. Defaults to|
. - wrap_all_strings (
bool
) – IfTrue
, wraps any string data in thewrapper_character
. IfNone
, only wraps string data if it contains thedelimiter
. Defaults toFalse
. - null_text (
str
) – The text value to use in place of empty values. Only applies ifwrap_empty_values
isTrue
. 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
) – IfTrue
, will double thewrapper_character
when it is found inside a column value. IfFalse
, will precede thewrapper_character
by theescape_character
when it is found inside a column value. Defaults toFalse
. - 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
.
Returns: Data from the object in CSV format ending in a newline (
\n
).Return type: - include_header (
-
to_dict
(max_nesting=0, current_nesting=0)¶ Return a
dict
representation of the object.Parameters: Returns: A
dict
representation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nesting
is greater thanmax_nesting
- MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
-
to_json
(max_nesting=0, current_nesting=0, serialize_function=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 to0
, will not nest other serializable objects. Defaults to0
. - current_nesting (
int
) – The current nesting level at which thedict
representation will reside. Defaults to0
. - 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 singledict
and return astr
, similar tosimplejson.dumps()
.If you wish to pass additional arguments to your
serialize_function
pass them as keyword arguments (inkwargs
). - 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: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nesting
is greater thanmax_nesting
- MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
- max_nesting (
-
to_yaml
(max_nesting=0, current_nesting=0, serialize_function=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 to0
, will not nest other serializable objects. Defaults to0
. - current_nesting (
int
) – The current nesting level at which the representation will reside. Defaults to0
. - serialize_function (callable /
None
) –Optionally override the default YAML serializer. Defaults to
None
, which calls the defaultyaml.dump()
function from the PyYAML library. - 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: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nesting
is greater thanmax_nesting
- MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
- max_nesting (
-
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')¶ 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 astr
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.
Raises: - DeserializationError – if
csv_data
is not a validstr
- CSVStructureError – if the columns in
csv_data
do not match the expected columns returned byget_csv_column_names()
- ValueDeserializationError – if a value extracted from the CSV failed when executing its de-serialization function.
- csv_data (
-
update_from_dict
(input_data, error_on_extra_keys=True, drop_extra_keys=False)¶ Update the model instance from data in a
dict
object.Parameters: - input_data (
dict
) – The inputdict
- error_on_extra_keys (
bool
) –If
True
, will raise an error if an unrecognized key is found ininput_data
. IfFalse
, will either drop or include the extra key in the result, as configured in thedrop_extra_keys
parameter. Defaults toTrue
.Warning
Be careful setting
error_on_extra_keys
toFalse
.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
) – IfTrue
, will omit unrecognized top-level keys from the resultingdict
. IfFalse
, will include unrecognized keys or raise an error based on the configuration of theerror_on_extra_keys
parameter. Defaults toFalse
.
Raises: - ExtraKeyError – if
error_on_extra_keys
isTrue
andinput_data
contains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_data
is not adict
or JSON object serializable to adict
or ifinput_data
is empty.
- input_data (
-
update_from_json
(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, **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 defaultsimplejson.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 singlestr
and return adict
, similar tosimplejson.loads()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (inkwargs
). - error_on_extra_keys (
bool
) –If
True
, will raise an error if an unrecognized key is found ininput_data
. IfFalse
, will either drop or include the extra key in the result, as configured in thedrop_extra_keys
parameter. Defaults toTrue
.Warning
Be careful setting
error_on_extra_keys
toFalse
.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
) – IfTrue
, will ignore unrecognized keys in the input data. IfFalse
, will include unrecognized keys or raise an error based on the configuration of theerror_on_extra_keys
parameter. Defaults toFalse
. - 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
isTrue
andinput_data
contains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_data
is not astr
JSON de-serializable object to adict
or ifinput_data
is empty.
- input_data (
-
update_from_yaml
(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, **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 astr
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 defaultyaml.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 singlestr
and return adict
, similar toyaml.safe_load()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (inkwargs
). - error_on_extra_keys (
bool
) –If
True
, will raise an error if an unrecognized key is found ininput_data
. IfFalse
, will either drop or include the extra key in the result, as configured in thedrop_extra_keys
parameter. Defaults toTrue
.Warning
Be careful setting
error_on_extra_keys
toFalse
.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
) – IfTrue
, will ignore unrecognized keys in the input data. IfFalse
, will include unrecognized keys or raise an error based on the configuration of theerror_on_extra_keys
parameter. Defaults toFalse
. - 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
isTrue
andinput_data
contains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_data
is not astr
YAML de-serializable object to adict
or ifinput_data
is empty.
- input_data (
-
primary_key_value
¶ The instance’s primary key.
Note
If not
None
, this value can always be passed toQuery.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 returnNone
.Return type: scalar / tuple
/None
-
classmethod
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 appropriatemapper
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 includeBaseModel
in that list of classes to mixin serialization/de-serialization support.If not
None
and not atuple
, will mixinBaseModel
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.
- cls (
@as_declarative¶
-
as_declarative
(**kw)[source]¶ Class decorator for
declarative_base()
.Provides a syntactical shortcut to the
cls
argument sent todeclarative_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 todeclarative_base()
.See also
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.
- 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 includeBaseModel
in that list of classes to mixin serialization/de-serialization support.If not
None
and not atuple
, will mixinBaseModel
with the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfiguration
or coercabledict
objects /None
) – Collection ofAttributeConfiguration
that determine the generated model’s serialization/de-serialization configuration. IfNone
, will support serialization and de-serialization across all keys inserialized_dict
. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized_json
that feature nested items (e.g. iterables, JSON objects, etc.) will be ignored. IfFalse
, will treat serialized items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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
) – Optionaldict
of special attributes that will be applied to the generatedBaseModel
(e.g.__table_args__
). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults toNone
. - 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 programmaticBaseModel
.
Returns: Model class whose structure matches
serialized
.Return type: Raises: - UnsupportedValueTypeError – when a value in
serialized
does not have a corresponding key intype_mapping
- ValueError – if
tablename
is empty - DeserializationError – if
serialized
is not a validstr
- CSVStructureError – if there are less than 2 (two) rows in
serialized
or if column headers are not valid Python variable names
- serialized (
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 defaultsimplejson.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 singlestr
and return adict
, similar tosimplejson.loads()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (indeserialize_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 includeBaseModel
in that list of classes to mixin serialization/de-serialization support.If not
None
and not atuple
, will mixinBaseModel
with the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfiguration
or coercabledict
objects /None
) – Collection ofAttributeConfiguration
that determine the generated model’s serialization/de-serialization configuration. IfNone
, will support serialization and de-serialization across all keys inserialized_dict
. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized_json
that feature nested items (e.g. iterables, JSON objects, etc.) will be ignored. IfFalse
, will treat serialized items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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
) – Optionaldict
of special attributes that will be applied to the generatedBaseModel
(e.g.__table_args__
). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults toNone
. - deserialize_kwargs (
dict
/None
) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults toNone
. - kwargs – Any additional keyword arguments will be passed to
declarative_base()
when generating the programmaticBaseModel
.
Returns: Model class whose structure matches
serialized
.Return type: Raises: - UnsupportedValueTypeError – when a value in
serialized
does not have a corresponding key intype_mapping
- ValueError – if
tablename
is empty
- serialized (
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 defaultyaml.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 singlestr
and return adict
, similar toyaml.safe_load()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (inkwargs
). - 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 includeBaseModel
in that list of classes to mixin serialization/de-serialization support.If not
None
and not atuple
, will mixinBaseModel
with the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfiguration
or coercabledict
objects /None
) – Collection ofAttributeConfiguration
that determine the generated model’s serialization/de-serialization configuration. IfNone
, will support serialization and de-serialization across all keys inserialized_dict
. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized_json
that feature nested items (e.g. iterables, JSON objects, etc.) will be ignored. IfFalse
, will treat serialized items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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
) – Optionaldict
of special attributes that will be applied to the generatedBaseModel
(e.g.__table_args__
). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults toNone
. - deserialize_kwargs (
dict
/None
) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults toNone
. - kwargs – Any additional keyword arguments will be passed to
declarative_base()
when generating the programmaticBaseModel
.
Returns: Model class whose structure matches
serialized
.Return type: Raises: - UnsupportedValueTypeError – when a value in
serialized
does not have a corresponding key intype_mapping
- ValueError – if
tablename
is empty
- serialized (
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
) – Thedict
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 includeBaseModel
in that list of classes to mixin serialization/de-serialization support.If not
None
and not atuple
, will mixinBaseModel
with the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfiguration
or coercabledict
objects /None
) – Collection ofAttributeConfiguration
that determine the generated model’s serialization/de-serialization configuration. IfNone
, will support serialization and de-serialization across all keys inserialized_dict
. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized_dict
that feature nested items (e.g. iterables,dict
objects, etc.) will be ignored. IfFalse
, will treat serialized items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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
) – Optionaldict
of special attributes that will be applied to the generatedBaseModel
(e.g.__table_args__
). Keys will correspond to the attribute name, while the value is the value that will be applied. Defaults toNone
. - kwargs – Any additional keyword arguments will be passed to
declarative_base()
when generating the programmaticBaseModel
.
Returns: Model class whose structure matches
serialized_dict
.Return type: Raises: - UnsupportedValueTypeError – when a value in
serialized_dict
does not have a corresponding key intype_mapping
- ValueError – if
serialized_dict
is not adict
or is empty - ValueError – if
tablename
is empty - ValueError – if
primary_key
is empty
- serialized_dict (
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. IfFalse
, 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. IfFalse
, 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. IfFalse
, 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 todict
and de-serialized from adict
. IfFalse
, will not be included when serialized todict
and will be ignored if present in a de-serializeddict
.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 adict
or de-serialized from adict
. - 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 defaulton_deserialize
function will be called instead.Tip
If you need to execute different
on_deserialize
functions for different formats, you can also supply adict
: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 defaulton_serialize
function will be called instead.Tip
If you need to execute different
on_serialize
functions for different formats, you can also supply adict
: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
.
- supports_csv (
-
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. IfFalse
, 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. IfFalse
, 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 todict
and de-serialized from adict
. IfFalse
, will not be included when serialized todict
and will be ignored if present in a de-serializeddict
.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 adict
or de-serialized from adict
.
- argument – see
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:
- SQLAlchemy:
sqlalchemy.schema.Table
- SQLAlchemy:
-
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.
- tablename (
str
) – The name of the SQL table to which the model corresponds. - metadata (
MetaData
) – aMetaData
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 particularConnectable
. - 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 applicableColumn
constructor. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized
that feature nested items (e.g. iterables,dict
objects, etc.) will be ignored. IfFalse
, will treat nested items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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 seesqlalchemy.schema.Table
.
Returns: A
Table
object.Return type: Raises: - DeserializationError – if
serialized
is not a validstr
- UnsupportedValueTypeError – when a value in
serialized
does not have a corresponding key intype_mapping
- ValueError – if
tablename
is empty - ValueError – if
primary_key
is empty - CSVStructureError – if there are less than 2 (two) rows in
serialized
or if column headers are not valid Python variable names
- serialized (
-
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 adict
.Parameters: - serialized (
dict
) – Thedict
that has been de-serialized from a given string. Keys will be treated as column names, while value data types will determineColumn
data types. - tablename (
str
) – The name of the SQL table to which the model corresponds. - metadata (
MetaData
) – aMetaData
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 particularConnectable
. - 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 applicableColumn
constructor. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized
that feature nested items (e.g. iterables,dict
objects, etc.) will be ignored. IfFalse
, will treat nested items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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 seesqlalchemy.schema.Table
.
Returns: A
Table
object.Return type: Raises: - UnsupportedValueTypeError – when a value in
serialized
does not have a corresponding key intype_mapping
- ValueError – if
serialized
is not adict
or is empty - ValueError – if
tablename
is empty - ValueError – if
primary_key
is empty
- serialized (
-
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
) – aMetaData
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 particularConnectable
. - 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 applicableColumn
constructor. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized
that feature nested items (e.g. iterables,dict
objects, etc.) will be ignored. IfFalse
, will treat nested items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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 defaultsimplejson.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 singlestr
and return adict
, similar tosimplejson.loads()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (indeserialize_kwargs
). - deserialize_kwargs (
dict
/None
) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults toNone
. - kwargs – Any additional keyword arguments will be passed to the
Table
constructor. For a full list of options, please seesqlalchemy.schema.Table
.
Returns: A
Table
object.Return type: Raises: - UnsupportedValueTypeError – when a value in
serialized
does not have a corresponding key intype_mapping
- DeserializationError – if
serialized
is not a validstr
- ValueError – if
tablename
is empty - ValueError – if
primary_key
is empty
- serialized (
-
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
) – aMetaData
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 particularConnectable
. - 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 applicableColumn
constructor. Defaults toNone
. - skip_nested (
bool
) – IfTrue
then any keys inserialized
that feature nested items (e.g. iterables,dict
objects, etc.) will be ignored. IfFalse
, will treat nested items asstr
. Defaults toTrue
. - default_to_str (
bool
) – IfTrue
, will automatically set a key/column whose value type cannot be determined tostr
(Text
). IfFalse
, will use the value type’s__name__
attribute and attempt to find a mapping. Defaults toFalse
. - 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 defaultyaml.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 singlestr
and return adict
, similar toyaml.safe_load()
.If you wish to pass additional arguments to your
deserialize_function
pass them as keyword arguments (inkwargs
). - deserialize_kwargs (
dict
/None
) – Optional additional keyword arguments that will be passed to the deserialize function. Defaults toNone
. - kwargs – Any additional keyword arguments will be passed to the
Table
constructor. For a full list of options, please seesqlalchemy.schema.Table
.
Returns: A
Table
object.Return type: Raises: - UnsupportedValueTypeError – when a value in
serialized
does not have a corresponding key intype_mapping
- DeserializationError – if
serialized
is not a validstr
- ValueError – if
tablename
is empty - ValueError – if
primary_key
is empty
- serialized (
-
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 toNone
. - 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. IfFalse
, 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. IfFalse
, 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. IfFalse
, 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 todict
and de-serialized from adict
. IfFalse
, will not be included when serialized todict
and will be ignored if present in a de-serializeddict
.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 adict
or de-serialized from adict
. - 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 defaulton_deserialize
function will be called instead.Tip
If you need to execute different
on_deserialize
functions for different formats, you can also supply adict
: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 defaulton_serialize
function will be called instead.Tip
If you need to execute different
on_serialize
functions for different formats, you can also supply adict
: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
.
- name (
-
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 inseq
and values invalue
.Parameters: - seq (iterable) – Iterable of keys
- value (iterable) – Iterable of values
Return type:
-
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 explicitcsv_sequence
provided.Return type: int
/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 defaulton_deserialize
function will be called instead.Tip
If you need to execute different
on_deserialize
functions for different formats, you can also supply adict
: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 defaulton_serialize
function will be called instead.Tip
If you need to execute different
on_serialize
functions for different formats, you can also supply adict
: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
)
-
validate_serialization_config()¶
-
validate_serialization_config
(config)[source]¶ Validate that
config
containsAttributeConfiguration
objects.Parameters: config (iterable of AttributeConfiguration
objects / iterable ofdict
objects corresponding to aAttributeConfiguration
/AttributeConfiguration
/dict
object corresponding to aAttributeConfiguration
) – Object or iterable of objects that representAttributeConfigurations
Return type: list
ofAttributeConfiguration
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
) – Theflask_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: Raises: - ImportError – if called when Flask-SQLAlchemy is not installed
- ValueError – if
db
is not an instance offlask_sqlalchemy.SQLAlchemy
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: - declarative_base (The declarative base model to combine with the automapped
model class produced.) – The declarative base class that is to be combined with
the
AutomapBase
class to construct the resulting automapped model class. To ensure that SQLAthanor serialization/de-serialization functionality is provided to your automapped model class, make sure that the value provided is produced bysqlathanor.declarative_base()
or otherwise inherits fromsqlathanor.declarative.BaseModel
. IfNone
, will default tosqlathanor.declarative.BaseModel
. - kwargs (keyword arguments) – Passed to
declarative_base()
Returns: A
AutomapBase
that can reflect your database schema structure with auto-generated declarative models that support SQLAthanor serialization/de-serialization.Return type: Raises: SQLAlchemySupportError – if called in an environment where SQLAlchemy is installed with a version less than 0.9.1 (which introduces automap support).
- declarative_base (The declarative base model to combine with the automapped
model class produced.) – The declarative base class that is to be combined with
the
SQLAthanor Internals¶
RelationshipProperty¶
-
class
RelationshipProperty
(argument, supports_json=False, supports_yaml=False, supports_dict=False, on_serialize=None, on_deserialize=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.