dservercore.sql_models
Database models and derived schemas
Classes
|
|
|
|
|
|
|
|
|
|
|
Always serialize datetime to float timestamp, and deserialize assuming UTC. |
|
|
|
|
|
- class dservercore.sql_models.FloatDateTimeField(*, load_default: ~typing.Any = <marshmallow.missing>, missing: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None, **additional_metadata)
Bases:
FieldAlways serialize datetime to float timestamp, and deserialize assuming UTC.
- __init__(*, load_default: ~typing.Any = <marshmallow.missing>, missing: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None, **additional_metadata) None
- property context
The context dictionary for the parent
Schema.
- property default
- default_error_messages = {'null': 'Field may not be null.', 'required': 'Missing data for required field.', 'validator_failed': 'Invalid value.'}
Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to
marshmallow.exceptions.ValidationError.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = None, **kwargs)
Deserialize
value.- Parameters:
value – The value to deserialize.
attr – The attribute/key in data to deserialize.
data – The raw input data passed to Schema.load.
kwargs – Field-specific keyword arguments.
- Raises:
ValidationError – If an invalid value is passed or if a required value is missing.
- fail(key: str, **kwargs)
Helper method that raises a ValidationError with an error message from
self.error_messages.Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.
- get_value(obj, attr, accessor=None, default=<marshmallow.missing>)
Return the value for a given key from an object.
- Parameters:
obj (object) – The object to get the value from.
attr (str) – The attribute/key in obj to get the value from.
accessor (callable) – A callable used to retrieve the value of attr from the object obj. Defaults to marshmallow.utils.get_value.
- make_error(key: str, **kwargs) ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = None, **kwargs)
Pulls the value for the given key from the object, applies the field’s formatting and returns the result.
- Parameters:
attr – The attribute/key to get from the object.
obj – The object to access the attribute/key from.
accessor – Function used to access values from
obj.kwargs – Field-specific keyword arguments.
- class dservercore.sql_models.User(**kwargs)
Bases:
Model- id
- username
- is_admin
- search_base_uris
- register_base_uris
- as_dict()
Return user using dictionary representation.
- __init__(**kwargs)
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- metadata = MetaData()
- query_class
alias of
Query
- registry = <sqlalchemy.orm.decl_api.registry object>
- query: t.ClassVar[Query]
A SQLAlchemy query for a model. Equivalent to
db.session.query(Model). Can be customized per-model by overridingquery_class.Warning
The query interface is considered legacy in SQLAlchemy. Prefer using
session.execute(select())instead.
- class dservercore.sql_models.BaseURI(**kwargs)
Bases:
Model- id
- base_uri
- search_users
- register_users
- datasets
- as_dict()
Return base URI using dictionary representation.
- __init__(**kwargs)
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- metadata = MetaData()
- query_class
alias of
Query
- registry = <sqlalchemy.orm.decl_api.registry object>
- query: t.ClassVar[Query]
A SQLAlchemy query for a model. Equivalent to
db.session.query(Model). Can be customized per-model by overridingquery_class.Warning
The query interface is considered legacy in SQLAlchemy. Prefer using
session.execute(select())instead.
- class dservercore.sql_models.Dataset(**kwargs)
Bases:
Model- id
- base_uri_id
- uri
- uuid
- name
- base_uri
- creator_username
- frozen_at
- created_at
- number_of_items
- size_in_bytes
- as_dict()
Return user using dictionary representation.
- __init__(**kwargs)
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in
kwargs.Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
- metadata = MetaData()
- query_class
alias of
Query
- registry = <sqlalchemy.orm.decl_api.registry object>
- query: t.ClassVar[Query]
A SQLAlchemy query for a model. Equivalent to
db.session.query(Model). Can be customized per-model by overridingquery_class.Warning
The query interface is considered legacy in SQLAlchemy. Prefer using
session.execute(select())instead.
- class dservercore.sql_models.BaseURISchema(*args, **kwargs)
Bases:
SQLAlchemyAutoSchema- class Meta
Bases:
object- exclude = ('id',)
- sqla_session = <flask_marshmallow.sqla.DummySession object>
- OPTIONS_CLASS
alias of
SQLAlchemyAutoSchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'str'>: <class 'marshmallow.fields.String'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>}
- __init__(*args, **kwargs)
- property dict_class: type
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
Serialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump(), except return a JSON-encoded string.- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
A
jsonstring
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.
- error_messages: Dict[str, str] = {}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters:
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
reprfor the class.
Added in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
Added in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
objandattr.
- get_instance(data)
Retrieve an existing record by primary key(s). If the schema instance is transient, return None.
- Parameters:
data – Serialized data to inform lookup.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters:
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
manyon dump or load.partial – Value of
partialon load.
Added in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- jsonify(obj: Any, many: bool | None = None, *args, **kwargs) Response
Return a JSON response containing the serialized data.
- Parameters:
obj – Object to serialize.
many (bool) – Whether obj should be serialized as an instance or as a collection. If None, defaults to the value of the many attribute on this Schema.
kwargs – Additional keyword arguments passed to flask.jsonify.
Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additional keyword arguments are passed to flask.jsonify.
Changed in version 0.6.3: The many argument for this method defaults to the value of the many attribute on the Schema. Previously, the many argument of this method defaulted to False, regardless of the value of Schema.many.
- load(data, *, session=None, instance=None, transient=False, **kwargs)
Deserialize data to internal representation.
- Parameters:
session – Optional SQLAlchemy session.
instance – Optional existing instance to modify.
transient – Optional switch to allow transient instantiation.
- loads(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)
Same as
load(), except it takes a JSON string as input.- Parameters:
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns:
Deserialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- make_instance(data, **kwargs)
Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in self.instance or loaded by primary key(s) in the data; else create a new row.
- Parameters:
data – Data to deserialize.
- on_bind_field(field_name: str, field_obj: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <flask_marshmallow.sqla.SQLAlchemyAutoSchemaOpts object>
- property session
- set_class
alias of
OrderedSet
- property transient
- validate(data, *, session=None, **kwargs)
Validate data against the schema, returning a dictionary of validation errors.
- Parameters:
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns:
A dictionary of validation errors.
Added in version 1.1.0.
- fields: Dict[str, ma_fields.Field]
Dictionary mapping field_names ->
Fieldobjects
- class dservercore.sql_models.BaseURIWithPermissionsSchema(*args, **kwargs)
Bases:
BaseURISchema- class Meta
Bases:
object- exclude = ('id',)
- sqla_session = <flask_marshmallow.sqla.DummySession object>
- OPTIONS_CLASS
alias of
SQLAlchemyAutoSchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'str'>: <class 'marshmallow.fields.String'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>}
- __init__(*args, **kwargs)
- property dict_class: type
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
Serialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump(), except return a JSON-encoded string.- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
A
jsonstring
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.
- error_messages: Dict[str, str] = {}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters:
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
reprfor the class.
Added in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
Added in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
objandattr.
- get_instance(data)
Retrieve an existing record by primary key(s). If the schema instance is transient, return None.
- Parameters:
data – Serialized data to inform lookup.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters:
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
manyon dump or load.partial – Value of
partialon load.
Added in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- jsonify(obj: Any, many: bool | None = None, *args, **kwargs) Response
Return a JSON response containing the serialized data.
- Parameters:
obj – Object to serialize.
many (bool) – Whether obj should be serialized as an instance or as a collection. If None, defaults to the value of the many attribute on this Schema.
kwargs – Additional keyword arguments passed to flask.jsonify.
Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additional keyword arguments are passed to flask.jsonify.
Changed in version 0.6.3: The many argument for this method defaults to the value of the many attribute on the Schema. Previously, the many argument of this method defaulted to False, regardless of the value of Schema.many.
- load(data, *, session=None, instance=None, transient=False, **kwargs)
Deserialize data to internal representation.
- Parameters:
session – Optional SQLAlchemy session.
instance – Optional existing instance to modify.
transient – Optional switch to allow transient instantiation.
- loads(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)
Same as
load(), except it takes a JSON string as input.- Parameters:
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns:
Deserialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- make_instance(data, **kwargs)
Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in self.instance or loaded by primary key(s) in the data; else create a new row.
- Parameters:
data – Data to deserialize.
- on_bind_field(field_name: str, field_obj: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <flask_marshmallow.sqla.SQLAlchemyAutoSchemaOpts object>
- property session
- set_class
alias of
OrderedSet
- property transient
- validate(data, *, session=None, **kwargs)
Validate data against the schema, returning a dictionary of validation errors.
- Parameters:
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns:
A dictionary of validation errors.
Added in version 1.1.0.
- exclude: set[Any] | MutableSet[Any]
- fields: Dict[str, ma_fields.Field]
Dictionary mapping field_names ->
Fieldobjects
- load_fields: Dict[str, ma_fields.Field]
- dump_fields: Dict[str, ma_fields.Field]
- class dservercore.sql_models.UserSchema(*args, **kwargs)
Bases:
SQLAlchemyAutoSchema- class Meta
Bases:
object- exclude = ('id',)
- sqla_session = <flask_marshmallow.sqla.DummySession object>
- OPTIONS_CLASS
alias of
SQLAlchemyAutoSchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'str'>: <class 'marshmallow.fields.String'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>}
- __init__(*args, **kwargs)
- property dict_class: type
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
Serialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump(), except return a JSON-encoded string.- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
A
jsonstring
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.
- error_messages: Dict[str, str] = {}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters:
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
reprfor the class.
Added in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
Added in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
objandattr.
- get_instance(data)
Retrieve an existing record by primary key(s). If the schema instance is transient, return None.
- Parameters:
data – Serialized data to inform lookup.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters:
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
manyon dump or load.partial – Value of
partialon load.
Added in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- jsonify(obj: Any, many: bool | None = None, *args, **kwargs) Response
Return a JSON response containing the serialized data.
- Parameters:
obj – Object to serialize.
many (bool) – Whether obj should be serialized as an instance or as a collection. If None, defaults to the value of the many attribute on this Schema.
kwargs – Additional keyword arguments passed to flask.jsonify.
Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additional keyword arguments are passed to flask.jsonify.
Changed in version 0.6.3: The many argument for this method defaults to the value of the many attribute on the Schema. Previously, the many argument of this method defaulted to False, regardless of the value of Schema.many.
- load(data, *, session=None, instance=None, transient=False, **kwargs)
Deserialize data to internal representation.
- Parameters:
session – Optional SQLAlchemy session.
instance – Optional existing instance to modify.
transient – Optional switch to allow transient instantiation.
- loads(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)
Same as
load(), except it takes a JSON string as input.- Parameters:
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns:
Deserialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- make_instance(data, **kwargs)
Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in self.instance or loaded by primary key(s) in the data; else create a new row.
- Parameters:
data – Data to deserialize.
- on_bind_field(field_name: str, field_obj: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <flask_marshmallow.sqla.SQLAlchemyAutoSchemaOpts object>
- property session
- set_class
alias of
OrderedSet
- property transient
- validate(data, *, session=None, **kwargs)
Validate data against the schema, returning a dictionary of validation errors.
- Parameters:
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns:
A dictionary of validation errors.
Added in version 1.1.0.
- fields: Dict[str, ma_fields.Field]
Dictionary mapping field_names ->
Fieldobjects
- class dservercore.sql_models.UserWithPermissionsSchema(*args, **kwargs)
Bases:
UserSchema- class Meta
Bases:
object- exclude = ('id',)
- sqla_session = <flask_marshmallow.sqla.DummySession object>
- OPTIONS_CLASS
alias of
SQLAlchemyAutoSchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'str'>: <class 'marshmallow.fields.String'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>}
- __init__(*args, **kwargs)
- property dict_class: type
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
Serialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump(), except return a JSON-encoded string.- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
A
jsonstring
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.
- error_messages: Dict[str, str] = {}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters:
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
reprfor the class.
Added in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
Added in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
objandattr.
- get_instance(data)
Retrieve an existing record by primary key(s). If the schema instance is transient, return None.
- Parameters:
data – Serialized data to inform lookup.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters:
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
manyon dump or load.partial – Value of
partialon load.
Added in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- jsonify(obj: Any, many: bool | None = None, *args, **kwargs) Response
Return a JSON response containing the serialized data.
- Parameters:
obj – Object to serialize.
many (bool) – Whether obj should be serialized as an instance or as a collection. If None, defaults to the value of the many attribute on this Schema.
kwargs – Additional keyword arguments passed to flask.jsonify.
Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additional keyword arguments are passed to flask.jsonify.
Changed in version 0.6.3: The many argument for this method defaults to the value of the many attribute on the Schema. Previously, the many argument of this method defaulted to False, regardless of the value of Schema.many.
- load(data, *, session=None, instance=None, transient=False, **kwargs)
Deserialize data to internal representation.
- Parameters:
session – Optional SQLAlchemy session.
instance – Optional existing instance to modify.
transient – Optional switch to allow transient instantiation.
- loads(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)
Same as
load(), except it takes a JSON string as input.- Parameters:
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns:
Deserialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- make_instance(data, **kwargs)
Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in self.instance or loaded by primary key(s) in the data; else create a new row.
- Parameters:
data – Data to deserialize.
- on_bind_field(field_name: str, field_obj: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <flask_marshmallow.sqla.SQLAlchemyAutoSchemaOpts object>
- property session
- set_class
alias of
OrderedSet
- property transient
- validate(data, *, session=None, **kwargs)
Validate data against the schema, returning a dictionary of validation errors.
- Parameters:
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns:
A dictionary of validation errors.
Added in version 1.1.0.
- exclude: set[Any] | MutableSet[Any]
- fields: Dict[str, ma_fields.Field]
Dictionary mapping field_names ->
Fieldobjects
- load_fields: Dict[str, ma_fields.Field]
- dump_fields: Dict[str, ma_fields.Field]
- class dservercore.sql_models.DatasetSchema(*args, **kwargs)
Bases:
SQLAlchemyAutoSchema- class Meta
Bases:
object- fields = ('base_uri', 'created_at', 'creator_username', 'frozen_at', 'name', 'uri', 'uuid')
- sqla_session = <flask_marshmallow.sqla.DummySession object>
- get_base_uri_string(obj)
Always serialize base_uri as string, no matter whether object is Dataset or simple dict
- OPTIONS_CLASS
alias of
SQLAlchemyAutoSchemaOpts
- TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'str'>: <class 'marshmallow.fields.String'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>}
- __init__(*args, **kwargs)
- property dict_class: type
- dump(obj: Any, *, many: bool | None = None)
Serialize an object to native Python data types according to this Schema’s fields.
- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
Serialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.
- dumps(obj: Any, *args, many: bool | None = None, **kwargs)
Same as
dump(), except return a JSON-encoded string.- Parameters:
obj – The object to serialize.
many – Whether to serialize obj as a collection. If None, the value for self.many is used.
- Returns:
A
jsonstring
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the serialized data rather than a
(data, errors)duple. AValidationErroris raised ifobjis invalid.
- error_messages: Dict[str, str] = {}
Overrides for default schema-level error messages
- classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type
Generate a Schema class given a dictionary of fields.
from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'}
Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.
- Parameters:
fields (dict) – Dictionary mapping field names to field instances.
name (str) – Optional name for the class, which will appear in the
reprfor the class.
Added in version 3.0.0.
- get_attribute(obj: Any, attr: str, default: Any)
Defines how to pull values from an object to serialize.
Added in version 2.0.0.
Changed in version 3.0.0a1: Changed position of
objandattr.
- get_instance(data)
Retrieve an existing record by primary key(s). If the schema instance is transient, return None.
- Parameters:
data – Serialized data to inform lookup.
- handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)
Custom error handler function for the schema.
- Parameters:
error – The ValidationError raised during (de)serialization.
data – The original input data.
many – Value of
manyon dump or load.partial – Value of
partialon load.
Added in version 2.0.0.
Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.
- jsonify(obj: Any, many: bool | None = None, *args, **kwargs) Response
Return a JSON response containing the serialized data.
- Parameters:
obj – Object to serialize.
many (bool) – Whether obj should be serialized as an instance or as a collection. If None, defaults to the value of the many attribute on this Schema.
kwargs – Additional keyword arguments passed to flask.jsonify.
Changed in version 0.6.0: Takes the same arguments as marshmallow.Schema.dump. Additional keyword arguments are passed to flask.jsonify.
Changed in version 0.6.3: The many argument for this method defaults to the value of the many attribute on the Schema. Previously, the many argument of this method defaulted to False, regardless of the value of Schema.many.
- load(data, *, session=None, instance=None, transient=False, **kwargs)
Deserialize data to internal representation.
- Parameters:
session – Optional SQLAlchemy session.
instance – Optional existing instance to modify.
transient – Optional switch to allow transient instantiation.
- loads(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)
Same as
load(), except it takes a JSON string as input.- Parameters:
json_data – A JSON string of the data to deserialize.
many – Whether to deserialize obj as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.
- Returns:
Deserialized data
Added in version 1.0.0.
Changed in version 3.0.0b7: This method returns the deserialized data rather than a
(data, errors)duple. AValidationErroris raised if invalid data are passed.
- make_instance(data, **kwargs)
Deserialize data to an instance of the model if self.load_instance is True.
Update an existing row if specified in self.instance or loaded by primary key(s) in the data; else create a new row.
- Parameters:
data – Data to deserialize.
- on_bind_field(field_name: str, field_obj: Field) None
Hook to modify a field when it is bound to the Schema.
No-op by default.
- opts: SchemaOpts = <flask_marshmallow.sqla.SQLAlchemyAutoSchemaOpts object>
- property session
- set_class
alias of
OrderedSet
- property transient
- validate(data, *, session=None, **kwargs)
Validate data against the schema, returning a dictionary of validation errors.
- Parameters:
data – The data to validate.
many – Whether to validate data as a collection. If None, the value for self.many is used.
partial – Whether to ignore missing fields and not require any fields declared. Propagates down to
Nestedfields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.
- Returns:
A dictionary of validation errors.
Added in version 1.1.0.
- fields: Dict[str, ma_fields.Field]
Dictionary mapping field_names ->
Fieldobjects