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
BaseModeldirectly 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_declarativedecorator:from sqlathanor import as_declarative @as_declarative class MyBaseModel(object): # Standard SQLAlchemy declarative model definition goes here.
-
classmethod
clear_serialization_cache()¶ Clears any cached serialization/de-serialization configurations.
Note
Does not affect the configuration itself - merely clears the heap caches if present.
-
classmethod
configure_serialization(configs=None, attributes=None, supports_csv=False, supports_json=False, supports_yaml=False, supports_dict=False, on_serialize=None, on_deserialize=None, config_set=None)¶ Apply configuration settings to the model class.
Caution
This method either overwrites the entire configuration (if no
config_setis supplied) set for the model class, or overwrites theconfig_setindicated.Tip
For this method, the configuration settings applied in
configsreceive priority over a configuration specified in keyword arguments.This means that if an attribute is configured in both
configsandattributes, the configuration inconfigswill apply.Parameters: - configs (iterable of
AttributeConfiguration/pydantic.main.ModelMetaclass/None) – Collection ofAttributeConfigurationobjects 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/tupleof 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/tupleof 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/tupleof 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/tupleof 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 todictand de-serialized from adict. IfFalse, will not be included when serialized todictand 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 /
dictwith 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_deserializefunctions 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 toNoneTip
To clear the
on_deserializefunction, you can either supply a value ofFalseor pass adictwith 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 /
dictwith 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_serializefunctions 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 toNoneTip
To clear the
on_serializefunction, you need to passFalseor adictwith 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.
- config_set (
str/None) – If notNone, will applyconfigsto the configuration set named. If the class does not use pre-existing configuration sets, will switch the class’ meta configuration to use configuration sets, with any pre-existing configuration assigned to a set named_original. Defaults toNone.
- 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, config_set=None)¶ Indicate whether
attributesupports 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 fromdictobjects. IfFalse, includes attribute names that cannot be de-serialized fromdictobjects. IfNone, will not include attributes based ondictde-serialization support (but may include them based on other parameters). Defaults toNone. - to_dict – If
True, includes attribute names that can be serialized todictobjects. IfFalse, includes attribute names that cannot be serialized todictobjects. IfNone, will not include attributes based ondictserialization support (but may include them based on other parameters). Defaults toNone. - config_set (
str/None) – If notNone, will determine serialization support within the indicated configuration set. Defaults toNone.
Returns: Trueif the attribute’s serialization support matches,Falseif not, andNoneif no serialization support was specified.Return type: Raises: - UnsupportedSerializationError – if
attributeis not present on the object - ValueError – if
config_setis notNoneand its value does not match a named configuration set - ConfigurationError – if
config_setisNoneand the object uses named configuration sets - ConfigurationError – if the object does not use configuration sets but
config_setis not None
- 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', config_set=None)¶ Retrieve a CSV representation of the object, with all attributes serialized regardless of configuration.
Caution
Nested objects (such as relationships or association proxies) will not be serialized.
Note
This method ignores any
display_namecontributed on theAttributeConfiguration.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_valuesisTrue. 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_characterwhen it is found inside a column value. IfFalse, will precede thewrapper_characterby theescape_characterwhen 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. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
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, config_set=None)¶ Return a
OrderedDictrepresentation 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 resultingOrderedDictobject can be nested. If set to0, will not nest other serializable objects. Defaults to0. - current_nesting (
int) – The current nesting level at which thedictrepresentation will reside. Defaults to0. - config_set (
str/None) – If notNone, the named configuration set to use when processing the input. Defaults toNone.
Returns: A
OrderedDictrepresentation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nestingis greater thanmax_nesting - MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
- max_nesting (
-
dump_to_json(max_nesting=0, current_nesting=0, serialize_function=None, config_set=None, **kwargs)¶ Return a JSON representation of the object, with all attributes regardless of configuration.
Caution
Nested objects (such as relationships or association proxies) will not be serialized.
Parameters: - max_nesting (
int) – The maximum number of levels that the resulting JSON object can be nested. If set to0, will not nest other serializable objects. Defaults to0. - current_nesting (
int) – The current nesting level at which thedictrepresentation 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_functionparameter to override the default JSON serializer.A valid
serialize_functionis expected to accept a singledictand return astr, similar tosimplejson.dumps().If you wish to pass additional arguments to your
serialize_functionpass them as keyword arguments (inkwargs). - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone. - 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
strwith the JSON representation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nestingis 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, config_set=None, **kwargs)¶ Return a YAML representation of the object with all attributes, regardless of configuration.
Caution
Nested objects (such as relationships or association proxies) will not be serialized.
Parameters: - max_nesting (
int) – The maximum number of levels that the resulting object can be nested. If set 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. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone. - 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
strwith the JSON representation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nestingis greater thanmax_nesting - MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
- max_nesting (
-
classmethod
get_attribute_serialization_config(attribute, config_set=None)¶ Retrieve the
AttributeConfigurationforattribute.Parameters: - attribute (
str) – The attribute/column name whose serialization configuration should be returned. - config_set (
str/None) – If notNone, will return theAttributeConfigurationobject forattributethat is contained within the named configuration set. Defaults toNone.
Returns: The
AttributeConfigurationforattribute.Return type: Raises: - ConfigurationError – if
config_setis not empty and there are no configuration sets defined onclsor if there are configuration sets defined but noconfig_setis specified - ValueError – if
config_setis not defined within__serialization__
- attribute (
-
classmethod
get_csv_column_names(deserialize=True, serialize=True, config_set=None)¶ 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. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
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', config_set=None)¶ Return the CSV representation of the model instance (record).
Parameters: - delimiter (
str) – The delimiter used between columns. Defaults to|. - wrap_all_strings (
bool) – 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_valuesisTrue. 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_characterwhen it is found inside a column value. IfFalse, will precede thewrapper_characterby theescape_characterwhen 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. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
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', config_set=None)¶ Retrieve a header string for a CSV representation of the model.
Parameters: - attributes (
listofstr) – 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_valuesisTrue. Defaults to'None'. - null_text – The text value to use in place of empty values. Only
applies if
wrap_empty_valuesisTrue. 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_characterwhen it is found inside a column value. IfFalse, will precede thewrapper_characterby theescape_characterwhen 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. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
Returns: A string ending in
line_terminatorwith the model’s CSV column names listed, separated by thedelimiter.Return type: - attributes (
-
classmethod
get_csv_serialization_config(deserialize=True, serialize=True, config_set=None)¶ Retrieve the CSV serialization configurations that apply for this object.
Parameters: - deserialize (
bool/None) – 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. - config_set (
str/None) – If notNone, the named configuration set whose CSV serialization configuration should be returned. Defaults toNone.
Returns: Set of attribute serialization configurations that match the arguments supplied.
Return type: Raises: - ConfigurationError – if
clsdoes not use named configuration sets butconfig_setis notNone - ConfigurationError – if
clsuses named configuration sets butconfig_setis empty - ValueError – if
config_setis not defined within__serialization__
- deserialize (
-
classmethod
get_dict_serialization_config(deserialize=True, serialize=True, config_set=None)¶ Retrieve the
dictserialization configurations that apply for this object.Parameters: - deserialize (
bool/None) – IfTrue, returns configurations for attributes that can be de-serialized fromdictobjects. IfFalse, returns configurations for attributes that cannot be de-serialized fromdictobjects. 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 todictobjects. IfFalse, returns configurations for attributes that cannot be serialized todictobjects. IfNone, ignores serialization configuration when determining which attribute configurations to return. Defaults toNone. - config_set (
str/None) – If notNone, the named configuration set whosedictserialization configuration should be returned. 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, config_set=None)¶ 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. - config_set (
str/None) – If notNone, the named configuration set whose JSON serialization configuration should be returned. 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: listofstr
-
classmethod
get_primary_key_columns()¶ Retrieve the model’s primary key columns.
Returns: listofColumnobjects corresponding to the table’s primary key(s).Return type: listofColumn
-
classmethod
get_serialization_config(from_csv=None, to_csv=None, from_json=None, to_json=None, from_yaml=None, to_yaml=None, from_dict=None, to_dict=None, exclude_private=True, config_set=None)¶ Retrieve a list of
AttributeConfigurationobjects 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 fromdictobjects. IfFalse, includes attribute names that cannot be de-serialized fromdictobjects. IfNone, will not include attributes based ondictde-serialization support (but may include them based on other parameters). Defaults toNone. - to_dict – If
True, includes attribute names that can be serialized todictobjects. IfFalse, includes attribute names that cannot be serialized todictobjects. IfNone, will not include attributes based ondictserialization 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. - config_set (
str/None) – If notNone, will return thoseAttributeConfigurationobjects that are contained within the named configuration set. Defaults toNone.
Returns: List of attribute configurations.
Return type: Raises: - ConfigurationError – if
clsdoes not use named configuration sets butconfig_setis notNone - ConfigurationError – if
clsuses named configuration sets butconfig_setis empty - ValueError – if
config_setis not defined within__serialization__
- from_csv (
-
classmethod
get_yaml_serialization_config(deserialize=True, serialize=True, config_set=None)¶ Retrieve the YAML serialization configurations that apply for this object.
Parameters: - deserialize (
bool/None) – 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. - config_set (
str/None) – If notNone, the named configuration set whose YAML serialization configuration should be returned. 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', config_set=None)¶ Create a new model instance from a CSV record.
Tip
Unwrapped empty column values are automatically interpreted as null (
None).Parameters: - csv_data (
str/ Path-like object) – The CSV data. If a Path-like object, will read the first record from a file that is assumed to include a header row. If astrand has more than one record (line), will assume the first line is a header row. - delimiter (
str) – The delimiter used between columns. Defaults to|. - wrapper_character (
str) – The string used to wrap string values when wrapping is applied. Defaults to'. - null_text (
str) – The string used to indicate an empty value if empty values are wrapped. Defaults to None. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
Returns: A model instance created from the record.
Return type: model instance
Raises: - DeserializationError – if
csv_datais not a validstr - CSVStructureError – if the columns in
csv_datado 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, config_set=None)¶ Update the model instance from data in a
dictobject.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_keysparameter. Defaults toTrue.Warning
Be careful setting
error_on_extra_keystoFalse.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_keysparameter. Defaults toFalse. - config_set (
str/None) – If notNone, the named configuration set to use when processing the input. Defaults toNone.
Raises: - ExtraKeyError – if
error_on_extra_keysisTrueandinput_datacontains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_datais not adictor JSON object serializable to adictor ifinput_datais empty.
- input_data (
-
classmethod
new_from_json(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)¶ Create a new model instance from data in JSON.
Parameters: - input_data (
stror Path-like object) –The JSON data to de-serialize.
Note
If
input_datapoints 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_functionparameter to override the default JSON deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar tosimplejson.loads().If you wish to pass additional arguments to your
deserialize_functionpass 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_keysparameter. Defaults toTrue.Warning
Be careful setting
error_on_extra_keystoFalse.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_keysparameter. Defaults toFalse. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone. - 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_keysisTrueandinput_datacontains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_datais not adictor JSON object serializable to adictor ifinput_datais empty.
- input_data (
-
classmethod
new_from_yaml(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)¶ Create a new model instance from data in YAML.
Parameters: - input_data (
str/ Path-like object) – The YAML data to de-serialize. May be either astror 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_functionparameter to override the default YAML deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar toyaml.safe_load().If you wish to pass additional arguments to your
deserialize_functionpass 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_keysparameter. Defaults toTrue.Warning
Be careful setting
error_on_extra_keystoFalse.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_keysparameter. Defaults toFalse. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
Raises: - ExtraKeyError – if
error_on_extra_keysisTrueandinput_datacontains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_datais not adictor JSON object serializable to adictor ifinput_datais 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, config_set=None)¶ Set the serialization/de-serialization configuration for
attribute.Note
Supplying keyword arguments like
supports_csvorsupports_jsonwill 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/ / PydanticModelFieldobject / /None) – TheAttributeConfigurationto apply. IfNone, will set particular values based on their corresponding keyword arguments. - supports_csv (
bool/tupleof 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/tupleof 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/tupleof 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/tupleof 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 todictand de-serialized from adict. IfFalse, will not be included when serialized todictand 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 /
dictwith 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_deserializefunctions 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 toNoneTip
To clear the
on_deserializefunction, you can either supply a value ofFalseor pass adictwith 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 /
dictwith 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_serializefunctions 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 toNoneTip
To clear the
on_serializefunction, you need to passFalseor adictwith 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_sequenceassigned, 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 - config_set (
str/None) –The name of the configuration set where the serialization/de-serialization configuration for
attributeshould be updated. Defaults toNoneWarning
If the
config_setis not defined on the model, then aConfigurationErrorwill be raised.
Raises: - ConfigurationError – if
config_setis not empty and there are no configuration sets defined onclsor if there are configuration sets defined but noconfig_setis specified - ValueError – if
config_setis not defined within__serialization__ - ValueError – if
attributedoes not matchconfig.nameifconfigis 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', config_set=None)¶ 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_valuesisTrue. 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_characterwhen it is found inside a column value. IfFalse, will precede thewrapper_characterby theescape_characterwhen 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. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
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, config_set=None)¶ Return a
OrderedDictrepresentation of the object.Parameters: - max_nesting (
int) – The maximum number of levels that the resultingdictobject can be nested. If set to0, will not nest other serializable objects. Defaults to0. - current_nesting (
int) – The current nesting level at which thedictrepresentation will reside. Defaults to0. - config_set (
str/None) – If notNone, the named configuration set to use when processing the input. Defaults toNone.
Returns: A
OrderedDictrepresentation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nestingis greater thanmax_nesting - MaximumNestingExceededWarning – if an attribute requires nesting
beyond
max_nesting
- max_nesting (
-
to_json(max_nesting=0, current_nesting=0, serialize_function=None, config_set=None, **kwargs)¶ Return a JSON representation of the object.
Parameters: - max_nesting (
int) – The maximum number of levels that the resulting JSON object can be nested. If set to0, will not nest other serializable objects. Defaults to0. - current_nesting (
int) – The current nesting level at which thedictrepresentation 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_functionparameter to override the default JSON serializer.A valid
serialize_functionis expected to accept a singledictand return astr, similar tosimplejson.dumps().If you wish to pass additional arguments to your
serialize_functionpass them as keyword arguments (inkwargs). - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone. - 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
strwith the JSON representation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nestingis 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, config_set=None, **kwargs)¶ Return a YAML representation of the object.
Parameters: - max_nesting (
int) – The maximum number of levels that the resulting object can be nested. If set 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. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone. - 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
strwith the JSON representation of the object.Return type: Raises: - SerializableAttributeError – if attributes is empty
- MaximumNestingExceededError – if
current_nestingis 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', config_set=None)¶ Update the model instance from a CSV record.
Tip
Unwrapped empty column values are automatically interpreted as null (
None).Parameters: - csv_data (
str/ Path-like object) – The CSV data. If a Path-like object, will read the first record from a file that is assumed to include a header row. If astrand has more than one record (line), will assume the first line is a header row. - delimiter (
str) – The delimiter used between columns. Defaults to|. - wrapper_character (
str) – The string used to wrap string values when wrapping is applied. Defaults to'. - null_text (
str) – The string used to indicate an empty value if empty values are wrapped. Defaults to None. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone.
Raises: - DeserializationError – if
csv_datais not a validstr - CSVStructureError – if the columns in
csv_datado 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, config_set=None)¶ Update the model instance from data in a
dictobject.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_keysparameter. Defaults toTrue.Warning
Be careful setting
error_on_extra_keystoFalse.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_keysparameter. Defaults toFalse. - config_set (
str/None) – If notNone, the named configuration set to use when processing the input. Defaults toNone.
Raises: - ExtraKeyError – if
error_on_extra_keysisTrueandinput_datacontains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_datais not adictor JSON object serializable to adictor ifinput_datais empty.
- input_data (
-
update_from_json(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)¶ Update the model instance from data in a JSON string.
Parameters: - input_data (
stror Path-like object) –The JSON data to de-serialize.
Note
If
input_datapoints 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_functionparameter to override the default JSON deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar tosimplejson.loads().If you wish to pass additional arguments to your
deserialize_functionpass 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_keysparameter. Defaults toTrue.Warning
Be careful setting
error_on_extra_keystoFalse.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_keysparameter. Defaults toFalse. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone. - 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_keysisTrueandinput_datacontains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_datais not astrJSON de-serializable object to adictor ifinput_datais empty.
- input_data (
-
update_from_yaml(input_data, deserialize_function=None, error_on_extra_keys=True, drop_extra_keys=False, config_set=None, **kwargs)¶ Update the model instance from data in a YAML string.
Parameters: - input_data (
str/ Path-like object) – The YAML data to de-serialize. May be either astror 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_functionparameter to override the default YAML deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar toyaml.safe_load().If you wish to pass additional arguments to your
deserialize_functionpass 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_keysparameter. Defaults toTrue.Warning
Be careful setting
error_on_extra_keystoFalse.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_keysparameter. Defaults toFalse. - config_set (
str/None) – If notNone, the named configuration set to use. Defaults toNone. - 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_keysisTrueandinput_datacontains top-level keys that are not recognized as attributes for the instance model. - DeserializationError – if
input_datais not astrYAML de-serializable object to adictor ifinput_datais 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
Noneif the instance is pending, in a transient state, or does not have a primary key.Returns: scalar or tuplevalue 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
Tableobjects and makes the appropriatemappercalls based on the information provided declaratively in the class and any subclasses of the class.Parameters: - cls (
None/tupleof classes / class object) –Defaults to
BaseModelto provide serialization/de-serialization support.If a
tupleof classes, will includeBaseModelin that list of classes to mixin serialization/de-serialization support.If not
Noneand not atuple, will mixinBaseModelwith 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
clsargument 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/tupleof classes / class object) –The base class to use when generating a new model class. Defaults to
BaseModelto provide serialization/de-serialization support.If a
tupleof classes, will includeBaseModelin that list of classes to mixin serialization/de-serialization support.If not
Noneand not atuple, will mixinBaseModelwith the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfigurationor coercabledictobjects /None) – Collection ofAttributeConfigurationthat 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) – IfTruethen any keys inserialized_jsonthat 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - base_model_attrs (
dict/None) – Optionaldictof 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
serializeddoes not have a corresponding key intype_mapping - ValueError – if
tablenameis empty - DeserializationError – if
serializedis not a validstr - CSVStructureError – if there are less than 2 (two) rows in
serializedor 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_functionparameter to override the default JSON deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar tosimplejson.loads().If you wish to pass additional arguments to your
deserialize_functionpass them as keyword arguments (indeserialize_kwargs). - cls (
None/tupleof classes / class object) –The base class to use when generating a new model class. Defaults to
BaseModelto provide serialization/de-serialization support.If a
tupleof classes, will includeBaseModelin that list of classes to mixin serialization/de-serialization support.If not
Noneand not atuple, will mixinBaseModelwith the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfigurationor coercabledictobjects /None) – Collection ofAttributeConfigurationthat 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) – IfTruethen any keys inserialized_jsonthat 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - base_model_attrs (
dict/None) – Optionaldictof 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
serializeddoes not have a corresponding key intype_mapping - ValueError – if
tablenameis 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_functionparameter to override the default YAML deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar toyaml.safe_load().If you wish to pass additional arguments to your
deserialize_functionpass them as keyword arguments (inkwargs). - cls (
None/tupleof classes / class object) –The base class to use when generating a new model class. Defaults to
BaseModelto provide serialization/de-serialization support.If a
tupleof classes, will includeBaseModelin that list of classes to mixin serialization/de-serialization support.If not
Noneand not atuple, will mixinBaseModelwith the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfigurationor coercabledictobjects /None) – Collection ofAttributeConfigurationthat 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) – IfTruethen any keys inserialized_jsonthat 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - base_model_attrs (
dict/None) – Optionaldictof 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
serializeddoes not have a corresponding key intype_mapping - ValueError – if
tablenameis 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) – Thedictthat 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/tupleof classes / class object) –The base class to use when generating a new model class. Defaults to
BaseModelto provide serialization/de-serialization support.If a
tupleof classes, will includeBaseModelin that list of classes to mixin serialization/de-serialization support.If not
Noneand not atuple, will mixinBaseModelwith the value passed to provide serialization/de-serialization support. - serialization_config (Iterable of
AttributeConfigurationor coercabledictobjects /None) – Collection ofAttributeConfigurationthat 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) – IfTruethen any keys inserialized_dictthat feature nested items (e.g. iterables,dictobjects, 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serialized_dictmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - base_model_attrs (
dict/None) – Optionaldictof 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_dictdoes not have a corresponding key intype_mapping - ValueError – if
serialized_dictis not adictor is empty - ValueError – if
tablenameis empty - ValueError – if
primary_keyis empty
- serialized_dict (
generate_model_from_pydantic()¶
-
generate_model_from_pydantic(pydantic_models, tablename, primary_key, cls=<class 'sqlathanor.declarative.base_model.BaseModel'>, skip_nested=True, default_to_str=False, type_mapping=None, base_model_attrs=None, **kwargs)[source]¶ Generate a model class from one or more Pydantic models.
Note
This function cannot programmatically create relationships, hybrid properties, or association proxies.
Parameters: - pydantic_models (
pydantic.BaseModel/ iterable ofpydantic.BaseModel/dictwhose keys correspond to configuration set names and whose value must be apydantic.BaseModel) –The Pydantic Model(s) which will determine the ORM columns/attributes that will be present within the generated model class.
Hint
If supplying an iterable of Pydantic models, then all models will be coalesced into a single model class. If supplying a
dictwhose values are separate Pydantic models, then eachdictkey will correspond to a single serialization/de-serialization configuration set in the resulting model class. - 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/tupleof classes / class object) –The base class to use when generating a new model class. Defaults to
BaseModelto provide serialization/de-serialization support.If a
tupleof classes, will includeBaseModelin that list of classes to mixin serialization/de-serialization support.If not
Noneand not atuple, will mixinBaseModelwith the value passed to provide serialization/de-serialization support. - skip_nested (
bool) – IfTruethen any keys inserialized_dictthat feature nested items (e.g. iterables,dictobjects, 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
pydantic_modelsmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - base_model_attrs (
dict/None) – Optionaldictof 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
pydantic_modelsand whose serialization/de-serialization configuration corresponds to the pattern implied bypydantic_modelsstructureReturn type: Raises: - UnsupportedValueTypeError – when a value in
pydantic_modelsdoes not have a corresponding key intype_mapping - ValueError – if
pydantic_modelsis not a supported type or is empty - ValueError – if
tablenameis empty - ValueError – if
primary_keyis empty
- pydantic_models (
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
Columnobject.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/tupleof 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_sequenceassigned, sorted alphabetically.If two columns have the same
csv_sequence, they will be sorted alphabetically. - supports_json (
bool/tupleof 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/tupleof 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/tupleof 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 todictand de-serialized from adict. IfFalse, will not be included when serialized todictand 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 adictor de-serialized from adict. - on_deserialize (callable /
dictwith 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_deserializefunction will be called instead.Tip
If you need to execute different
on_deserializefunctions 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 /
dictwith 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_serializefunction will be called instead.Tip
If you need to execute different
on_serializefunctions 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/tupleof 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/tupleof 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/tupleof 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 todictand de-serialized from adict. IfFalse, will not be included when serialized todictand 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 adictor 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
Tableobject.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
Tableobject 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) – aMetaDataobject 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 applicableColumnconstructor. Defaults toNone. - skip_nested (
bool) – IfTruethen any keys inserializedthat feature nested items (e.g. iterables,dictobjects, 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - 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
Tableconstructor. For a full list of options, please seesqlalchemy.schema.Table.
Returns: A
Tableobject.Return type: Raises: - DeserializationError – if
serializedis not a validstr - UnsupportedValueTypeError – when a value in
serializeddoes not have a corresponding key intype_mapping - ValueError – if
tablenameis empty - ValueError – if
primary_keyis empty - CSVStructureError – if there are less than 2 (two) rows in
serializedor 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
Tableobject from adict.Parameters: - serialized (
dict) – Thedictthat has been de-serialized from a given string. Keys will be treated as column names, while value data types will determineColumndata types. - tablename (
str) – The name of the SQL table to which the model corresponds. - metadata (
MetaData) – aMetaDataobject 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 applicableColumnconstructor. Defaults toNone. - skip_nested (
bool) – IfTruethen any keys inserializedthat feature nested items (e.g. iterables,dictobjects, 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - kwargs – Any additional keyword arguments will be passed to the
Tableconstructor. For a full list of options, please seesqlalchemy.schema.Table.
Returns: A
Tableobject.Return type: Raises: - UnsupportedValueTypeError – when a value in
serializeddoes not have a corresponding key intype_mapping - ValueError – if
serializedis not adictor is empty - ValueError – if
tablenameis empty - ValueError – if
primary_keyis 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
Tableobject 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
Columndata 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) – aMetaDataobject 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 applicableColumnconstructor. Defaults toNone. - skip_nested (
bool) – IfTruethen any keys inserializedthat feature nested items (e.g. iterables,dictobjects, 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - 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_functionparameter to override the default JSON deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar tosimplejson.loads().If you wish to pass additional arguments to your
deserialize_functionpass 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
Tableconstructor. For a full list of options, please seesqlalchemy.schema.Table.
Returns: A
Tableobject.Return type: Raises: - UnsupportedValueTypeError – when a value in
serializeddoes not have a corresponding key intype_mapping - DeserializationError – if
serializedis not a validstr - ValueError – if
tablenameis empty - ValueError – if
primary_keyis 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
Tableobject 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
Columndata 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) – aMetaDataobject 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 applicableColumnconstructor. Defaults toNone. - skip_nested (
bool) – IfTruethen any keys inserializedthat feature nested items (e.g. iterables,dictobjects, 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - 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_functionparameter to override the default YAML deserializer.A valid
deserialize_functionis expected to accept a singlestrand return adict, similar toyaml.safe_load().If you wish to pass additional arguments to your
deserialize_functionpass 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
Tableconstructor. For a full list of options, please seesqlalchemy.schema.Table.
Returns: A
Tableobject.Return type: Raises: - UnsupportedValueTypeError – when a value in
serializeddoes not have a corresponding key intype_mapping - DeserializationError – if
serializedis not a validstr - ValueError – if
tablenameis empty - ValueError – if
primary_keyis empty
- serialized (
-
classmethod
from_pydantic(models, tablename, metadata, primary_key, skip_nested=True, default_to_str=False, type_mapping=None, **kwargs)[source]¶ Generate a
Tableobject from one or more Pydantic models.Parameters: - models (
pydantic.BaseModel/ iterable ofpydantic.BaseModel/dictwhose keys correspond to configuration set names and whose value must be apydantic.BaseModel) –The Pydantic model(s) which will determine the columns/attributes that will be present within the generated table.
Hint
If supplying an iterable of Pydantic models, then all models will be coalesced into a single
Table. If supplying adictwhose values are separate Pydantic models, then eachdictkey will correspond to a single serialization/de-serialization configuration set in the resulting model class. - tablename (
str) – The name of the SQL table to which the model corresponds. - metadata (
MetaData) – aMetaDataobject 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. - skip_nested (
bool) – IfTruethen any keys inserializedthat feature nested items (e.g. iterables,dictobjects, 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 (
dictwith type names as keys and column data types as values.) –Determines how value types in
serializedmap 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 boolBooleanstrTextintIntegerfloatFloatdateDatedatetimeDateTimetimeTime - kwargs – Any additional keyword arguments will be passed to the
Tableconstructor. For a full list of options, please seesqlalchemy.schema.Table.
Returns: A
Tableobject.Return type: Raises: - UnsupportedValueTypeError – when a value in
serializeddoes not have a corresponding key intype_mapping - ValueError – if
modelsis empty or is not an acceptable type - ValueError – if
tablenameis empty - ValueError – if
primary_keyis empty
- models (
-
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
AttributeConfigurationobject.Parameters: - name (
str) – The name of the attribute. Defaults toNone. - supports_csv (
bool/tupleof 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/tupleof 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/tupleof 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/tupleof 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 todictand de-serialized from adict. IfFalse, will not be included when serialized todictand 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 adictor de-serialized from adict. - on_deserialize (callable /
dictwith 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_deserializefunction will be called instead.Tip
If you need to execute different
on_deserializefunctions 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 /
dictwith 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_serializefunction will be called instead.Tip
If you need to execute different
on_serializefunctions 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_sequenceassigned, sorted alphabetically.If two columns have the same
csv_sequence, they will be sorted alphabetically. - attribute (class attribute) – The object representation of an attribute. Supplying this
value overrides any other configuration options supplied. Defaults to
None. - display_name (
str/None) – An optional name to use or expect in place of name when serializing or de-serializing the attribute. IfNone, the attribute will default to the same name as in its Python model class and as provided inname. Defaults toNone - pydantic_field (
pydantic.fields.ModelField/pydantic.fields.FieldInfo/None) –An optional Pydantic
ModelFieldwhich can be used to validate the attribute on serialization. Defaults toNone.Note
If present, values will be validated against the Pydantic field after any
on_deserializefunction is executed.
- name (
-
classmethod
from_pydantic_model(model, name, **kwargs)[source]¶ Return a new
AttributeConfigurationinstance produced from a Pydantic model’s field definition forname.Parameters: - model (Pydantic
ModelMetaclass) – The Pydantic model whose field should be used. - name (
str) – The name of the field to convert to convert to anAttributeConfiguration - supports_csv (
bool/tupleof 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/tupleof 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/tupleof 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/tupleof 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 todictand de-serialized from adict. IfFalse, will not be included when serialized todictand 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 adictor de-serialized from adict. - on_deserialize (callable /
dictwith 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_deserializefunction will be called instead.Tip
If you need to execute different
on_deserializefunctions 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 /
dictwith 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_serializefunction will be called instead.Tip
If you need to execute different
on_serializefunctions 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_sequenceassigned, sorted alphabetically.If two columns have the same
csv_sequence, they will be sorted alphabetically.
Returns: An
AttributeConfigurationfor attributenamederived from the Pydantic model.Return type: Raises: - ValueError – if
modelis not a PydanticModelMetaclass - validator_collection.errors.InvalidVariableName – if
nameis not a valid variable name - FieldNotFoundError – if a field with
nameis not found withinmodel
- model (Pydantic
-
classmethod
from_attribute(attribute)[source]¶ Return an instance of
AttributeConfigurationconfigured for a given attribute.
-
classmethod
from_pydantic_model(model, name, **kwargs)[source] Return a new
AttributeConfigurationinstance produced from a Pydantic model’s field definition forname.Parameters: - model (Pydantic
ModelMetaclass) – The Pydantic model whose field should be used. - name (
str) – The name of the field to convert to convert to anAttributeConfiguration - supports_csv (
bool/tupleof 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/tupleof 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/tupleof 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/tupleof 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 todictand de-serialized from adict. IfFalse, will not be included when serialized todictand 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 adictor de-serialized from adict. - on_deserialize (callable /
dictwith 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_deserializefunction will be called instead.Tip
If you need to execute different
on_deserializefunctions 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 /
dictwith 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_serializefunction will be called instead.Tip
If you need to execute different
on_serializefunctions 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_sequenceassigned, sorted alphabetically.If two columns have the same
csv_sequence, they will be sorted alphabetically.
Returns: An
AttributeConfigurationfor attributenamederived from the Pydantic model.Return type: Raises: - ValueError – if
modelis not a PydanticModelMetaclass - validator_collection.errors.InvalidVariableName – if
nameis not a valid variable name - FieldNotFoundError – if a field with
nameis not found withinmodel
- model (Pydantic
-
classmethod
fromkeys(seq, value=None)[source]¶ Create a new
AttributeConfigurationwith keys inseqand 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_sequenceprovided.Return type: int/None.
-
display_name¶ The property name to apply when serializing the attribute or to expect when de-serializing.
Note
If
None, will default to the attribute name in the Python model class.Return type: str/None.
-
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_deserializefunction will be called instead.Tip
If you need to execute different
on_deserializefunctions 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 / dictwith 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_serializefunction will be called instead.Tip
If you need to execute different
on_serializefunctions 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 / dictwith formats as keys and values as callables
-
pydantic_field¶ A Pydantic
ModelFieldobject that can be used to validate the attribute. Defaults toNone.Return type: pydantic.fields.ModelField/pydantic.fields.FieldInfo/None
-
supports_csv¶ Indicates whether the attribute can be serialized / de-serialized to CSV.
Returns: 2-member tuple(inbound de-serialization / outbound serialization)Return type: tupleof 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: tupleof form (bool,bool)
-
validate_serialization_config()¶
-
validate_serialization_config(config)[source]¶ Validate that
configcontains or can be converted toAttributeConfigurationobjects.Parameters: config (iterable of AttributeConfigurationobjects / iterable ofdictobjects corresponding to aAttributeConfiguration/AttributeConfiguration/dictobject corresponding to aAttributeConfiguration/pydantic.main.ModelMetaclassobject whose fields correspond toAttributeConfigurationobjects) – Object or iterable of objects that representAttributeConfigurationsReturn type: listofAttributeConfigurationobjects
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.SQLAlchemyinstance.Returns: A mutated instance of
dbthat 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
dbis 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_classwhen 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
AutomapBaseclass as well as a declarative base that you supply.If no declarative base is supplied, then the SQLAthanor default
BaseModelwill 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
AutomapBaseclass 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
AutomapBasethat 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, display_name=None, **kwargs)[source]¶ Describes an object property that holds a single item or list of items that correspond to a related database table.
Public constructor is the
sqlathanor.schema.relationship()function.