API Reference¶
Schemas¶
drowsy.schema¶
Classes for building REST API friendly, model based schemas.
- class drowsy.schema.ResourceSchemaOpts(meta, *args, **kwargs)[source]¶
Meta class options for use with a
ModelResourceSchema.instance_cls` must be set.
Defaults
id_keystoNone, meaning the actual resource class using these opts must manually override its memberid_keysproperty.Example usage:
class UserSchema(ResourceSchema): class Meta: # Use username to identify a user resource # rather than user_id. id_keys = ["username"] # Give a class to be used for initializing # new instances for this resource. instance_cls = User # Custom schema level error messages error_messages = { "permission_denied": "Don't do that." }
- class drowsy.schema.ModelResourceSchemaOpts(meta, *args, **kwargs)[source]¶
Meta class options for use with a
ModelResourceSchema.Defaults
model_convertertoModelResourceConverter.Defaults
id_keystoNone, resulting in the model’s primary keys being used as identifier fields.Overwrites
instance_clsfromResourceSchemaOptstomodel.Example usage:
class UserSchema(ModelResourceSchema): class Meta: # Note that model will overwrite instance_cls model = User # Use username to identify a user resource # rather than user_id. id_keys = ["username"] # Alternate converter to dump/load with camel case. model_converter = CamelModelResourceConverter
- class drowsy.schema.ResourceSchema(only=None, exclude=(), many=None, load_only=(), dump_only=(), partial=None, unknown=None, context=None, instance=None, parent_resource=None, error_messages=None)[source]¶
Schema meant to be used with a Resource.
Enables sub-resource embedding, context processing, error translation, and more.
- OPTIONS_CLASS¶
alias of
ResourceSchemaOpts
- __init__(only=None, exclude=(), many=None, load_only=(), dump_only=(), partial=None, unknown=None, context=None, instance=None, parent_resource=None, error_messages=None)[source]¶
Sets additional member vars on top of ResourceSchema.
Also runs
process_context()upon completion.- Parameters:
only (tuple or list or None) – Fields to be included in the serialized result.
exclude (tuple or list) – Fields to be excluded from the serialized result.
many (bool) –
Trueif loading a collection of items.load_only (tuple or list) – Fields to be skipped during serialization.
dump_only (tuple|list) – Fields to be skipped during deserialization.
partial (bool) – Ignores missing fields when deserializing if
True.unknown (
UnknownOption) – How to handle unknown fields in provided data. Can be EXCLUDE, INCLUDE, or RAISE.context (dict or None) – Dictionary of values relevant to the current execution context. Should have a gettext key and callable value for that key if you’re intending to translate error messages.
instance – Object instance data should be loaded into. If
Noneis provided, an instance will either be determined using the provided data viaget_instance(), or if that fails a new instance will be created.parent_resource (
BaseResourceABCor None) – The parent resource that owns this schema.
- make_error(key, data=None, **kwargs)[source]¶
Raises an exception based on the
keyprovided.- Parameters:
- Returns:
PermissionValidationError exception if
keyis"permission_denied", otherwise a ValidationError.
- property fields_by_data_key¶
Get a dictionary of fields with data_key as the keys.
- Returns:
Dictionary of fields with the keys coming from field.data_key.
- Return type:
- get_instance(data)[source]¶
Used primarily to retrieve a pre-existing instance.
Should use the provided
datato locate the pre-existing instance, but not to populate it.- Parameters:
data (dict) – Data associated with this instance.
- Returns:
An object instance if it already exists, or None.
- Raises:
ValidationError – If the
id_keysindataare of the wrong type.
- embed(items)[source]¶
Embed the list of field names provided.
- Parameters:
items (list or str) – A list or single instance of embeddable sub resources or sub resource fields.
- Returns:
None
- Return type:
None
- Raises:
AttributeError – If the schema does not contain the specified field to embed.
- property id_keys¶
Get the fields used to identify a resource instance.
- make_instance(data, **kwargs)[source]¶
Deserialize the provided data into an object instance.
- Parameters:
data – The data to be deserialized into an instance.
- Returns:
An object instance with the provided data deserialized into it.
- load(data, *, many=None, partial=None, unknown=None, instance=None, action=None, **kwargs)[source]¶
Deserialize the provided data into an object.
- Parameters:
data (dict|list<dict>) – Data to be loaded into an instance.
many (bool|None) – True if loading a collection. None defers to the schema default, other values will act as an override.
partial (bool) – Ignores missing fields when deserializing if
True.unknown (
UnknownOption) – How to handle unknown fields in provided data. Can be EXCLUDE, INCLUDE, or RAISE.instance – Object instance that data should be loaded into. If
Noneis provided at this point or when the class was initialized, an instance will either be determined using the provided data viaget_instance(), or if that fails a new instance will be created.action (str|None) – Used as part of a permissions check. Possible values include “create” if a new object is being created, “update” is an existing object is being updated, or “delete” if the object is to be deleted. If None is provided, the method will deduce the action based on whether an existing instance is found in the database (“update”) or not (“create”). If loading a collection, any value passed will be applied to all objects.
- Returns:
An instance with the provided data loaded into it.
- Raises:
ValidationError – If any errors are encountered.
PermissionValidationError – If any of the actions being taken are not allowed.
- handle_preexisting_create(data)[source]¶
Handles trying to create an object that already exists.
You’ll have to override this if you want to treat the
"create"action like"update"on a pre-existing object.- Parameters:
data (dict) – The user supplied data that triggered this issue.
- Returns:
None
- Raises:
ValidationError – If not allowed.
- check_permission(data, instance, action)[source]¶
Checks if this action is permissible to attempt.
Does nothing by default, but can be overridden to check if a create, update, or delete action is permissible before performing any other validation or attempting the action.
- Parameters:
- Returns:
None
- Raises:
PermissionValidationError – If the action being taken is not allowed.
- class drowsy.schema.ModelResourceSchema(only=None, exclude=(), many=False, context=None, load_only=(), dump_only=(), partial=False, unknown=None, instance=None, parent_resource=None, session=None)[source]¶
Schema meant to be used with a ModelResource.
Enables sub-resource embedding, context processing, error translation, and more.
- OPTIONS_CLASS¶
alias of
ModelResourceSchemaOpts
- __init__(only=None, exclude=(), many=False, context=None, load_only=(), dump_only=(), partial=False, unknown=None, instance=None, parent_resource=None, session=None)[source]¶
Sets additional member vars on top of SQLAlchemyAutoSchema.
Also runs
process_context()upon completion.- Parameters:
only (tuple or list or None) – Fields to be included in the serialized result.
exclude (tuple or list) – Fields to be excluded from the serialized result.
many (bool) –
Trueif loading a collection of items.context (dict or None) – Dictionary of values relevant to the current execution context. Should have a gettext key and callable value for that key if you’re intending to translate error messages.
load_only (tuple or list) – Fields to be skipped during serialization.
dump_only (tuple or list) – Fields to be skipped during deserialization.
partial (bool) – Ignores missing fields when deserializing if
True.instance – SQLAlchemy model instance data should be loaded into. If
Noneis provided, an instance will either be determined using the provided data viaget_instance(), or if that fails a new instance will be created.parent_resource (
ModelResourceor None) – The parent resource that owns this schema.session – SQLAlchemy database session.
- get_instance(data)[source]¶
Retrieve an existing record by primary key(s).
- Parameters:
data (dict) – Data associated with this instance.
- Returns:
An instance fetched from the database using the value of the
id_keysindata.- Raises:
ValidationError – If the
id_keysindataare of the wrong type.
- property id_keys¶
Get the fields used to identify a resource instance.
- load(data, *, many=None, partial=None, unknown=None, instance=None, action=None, session=None, **kwargs)[source]¶
Deserialize the provided data into a SQLAlchemy object.
- Parameters:
data (dict|list<dict>) – Data to be loaded into an instance.
many (bool|None) – True if loading a collection. None defers to the schema default, other values will act as an override.
partial (bool) – Ignores missing fields when deserializing if
True.unknown (
UnknownOption) – How to handle unknown fields in provided data. Can be EXCLUDE, INCLUDE, or RAISE.instance – SQLAlchemy model instance data should be loaded into. If
Noneis provided at this point or when the class was initialized, an instance will either be determined using the provided data viaget_instance(), or if that fails a new instance will be created.action (str|None) – Used as part of a permissions check. Possible values include “create” if a new object is being created, “update” is an existing object is being updated, or “delete” if the object is to be deleted. If None is provided, the method will deduce the action based on whether an existing instance is found in the database (“update”) or not (“create”). If loading a collection, any value passed will be applied to all objects.
session – Optional database session. Will be used in place of
self.sessionif provided.
- Returns:
An instance with the provided data loaded into it.
- Raises:
ValidationError – If any errors are encountered.
PermissionValidationError – If any of the actions being taken are not allowed.
- exclude: set[Any] | MutableSet[Any]¶
- unknown: types.UnknownOption¶
Resources¶
drowsy.resource¶
Base classes for building resources and model resources.
- class drowsy.resource.PaginationInfo(resources_available, page_size=None, current_page=None)[source]¶
Pagination meta info container.
- __init__(resources_available, page_size=None, current_page=None)[source]¶
Initializes pagination info container.
- property page_size¶
Get the number of resources included in a result collection.
- Returns:
The size of each page in a result collection.
- Return type:
int or None
- property current_page¶
Get the current page of this resource collection.
- Returns:
The current page of this resource collection.
- Return type:
int or None
- property first_page¶
Get the first page number of this resource collection.
- Returns:
1if pagination is being used, otherwiseNone.- Return type:
int or None
- property last_page¶
Get the last page number of this resource collection.
- Returns:
The number of the last page if pagination is being used, otherwise
None.- Return type:
int or None
- class drowsy.resource.ResourceCollection(resources, resources_available, page_size=None, current_page=None)[source]¶
A simple list subclass that contains some extra meta info.
- __init__(resources, resources_available, page_size=None, current_page=None)[source]¶
Initializes a resource collection.
- Parameters:
resources (iterable) – The resources that were fetched in a query.
resources_available (int) – The total number of matching resources for a query. Used for pagination info.
page_size (int or None) – The current page number for the result.
current_page (int or None) – The current page number for the result.
- class drowsy.resource.ResourceOpts(meta)[source]¶
Meta class options for use with a SchemaResource.
A
schema_clsoption must be provided.An
optionsoption may be provided as a list in order to explicitly state what actions may be taken on this resource, with GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS as possible values.An
error_messagesoption may be provided as a dict in order to override some or all of the default error messages for a resource.A
page_max_sizeoption may be provided as an int, callable, orNoneto specify default page size for this resource. If given a callable, it should the resource itself as an argument.Example usage:
class UserResource(ModelResource): class Meta: schema_cls = UserSchema options = ["GET", "POST", "PUT", "PATCH] error_messages = { "validation_failure": "Fix your data." } page_max_size = 100
- __init__(meta)[source]¶
Handle the meta class attached to a ModelResource.
- Parameters:
meta – The meta class attached to a
ModelResource.
- class drowsy.resource.ResourceMeta(name, bases, attrs)[source]¶
Meta class inherited by ModelResource.
This is ultimately responsible for attaching an
optsobject toModelResource, as well as registering that class with theresource_class_registry.- __init__(name, bases, attrs)[source]¶
Initializes the meta class for a
ModelResourceclass.- Parameters:
cls – This
ResourceMetaclass.name – Class name of the
ModelResourcethat this meta class is attached to.bases (tuple) – Base classes the associated class inherits from.
attrs (dict) – Dictionary of info pertaining to the class this meta class is attached to. Includes the __module__ the class is in, the __qualname__ of the class, and potentially __doc__ for the class.
- class drowsy.resource.BaseModelResource(session, context=None, page_max_size=None, error_messages=None, parent_field=None)[source]¶
Model API Resources should inherit from this object.
- OPTIONS_CLASS¶
alias of
ResourceOpts
- __init__(session, context=None, page_max_size=None, error_messages=None, parent_field=None)[source]¶
Creates a new instance of the model.
- Parameters:
session (
Sessionor callable) – Database session to use for any resource actions.context (dict, callable, or None) – Context used to alter the schema used for this resource. For example, may contain the current authorization status of the current request. If errors should be translated, context should include a
"gettext"key referencing a callable that takes in a string and any keyword args.page_max_size (int, callable, or None) – Used to determine the maximum number of results to return by
get_collection(). Defaults to thepage_max_sizefrom the resource’soptsifNoneis passed in. To explicitly allow no limit, pass in0. If given acallable, it should accept the resource itself as its first and only argument.error_messages (dict or None) – May optionally be provided to override the default error messages for this resource.
parent_field (Field) – The field that owns this resource, if applicable. Likely some variety of
NestedPermissibleABC.
- make_error(key, errors=None, exc=None, **kwargs)[source]¶
Returns an exception based on the
keyprovided.- Parameters:
key (str) – Failure type, used to choose an error message.
errors (dict or None) – May be used by the raised exception.
exc (
Exceptionor None) – If another exception triggered this failure, it may be provided for a more informative failure. In the case of anInvalidMqlExceptionbeing provided, theexc.messagewill be used as part of the error message here.kwargs – Any additional arguments that may be used for generating an error message.
- Returns:
UnprocessableEntityError If
keyis"validation_failure". Note that in this case, errors should preferably be provided. In all other cases a BadRequestError is returned.
- property model¶
Get the model class associated with this resource.
- property session¶
Get a db session to use for this request.
- property query_builder¶
Returns a ModelResourceQueryBuilder object.
This exists mainly for inheritance purposes.
- get_required_filters(alias=None)[source]¶
Build any required filters for this resource.
Does nothing by default, but can be usefully overridden if you want to enforce certain filters on this resource. A simple example would be a notifications resource where a filter matching the currently logged in user is applied.
e.g.:
model = alias or self.model return model.user_id == self.context.get("user_id")
- Parameters:
alias – Can optionally be supplied if this resource is being used as a subresource and an alias has been applied.
- Returns:
Any valid SQL expression(s), to be passed directly into
filter(). If multiple expressions, they may be returned in a list or tuple. Defaults toNone.
- get_required_nested_filters(key)[source]¶
For a given dot separated data key, return required filters.
Uses
get_required_filters()from child resources.- Parameters:
key (str) – Dot notation field name. For example, if trying to query an album, this may look something like
"tracks.playlists".- Returns:
Any valid SQL expression(s), to be passed directly into
filter(). If multiple expressions, they may be returned in a list or tuple. Defaults toNone.
- apply_required_filters(query, alias=None)[source]¶
Apply required filters on this query.
Applies the result of
get_required_filters()directly to the providedquery.If you’re looking to define any required filters for a resource, you’ll want to override
get_required_filters()rather than this method. Doing so ensures those filters are applied when the resource is used as a child resource as well.- Parameters:
query (
Select) – An already partially constructed sqlalchemy query.alias – Can optionally be used if this resource is being used as a subresource and an alias has been applied.
- Returns:
A potentially modified query object.
- Return type:
Query
- property options¶
Get the available options for this resource.
- Returns:
A list of available options for this resource. Values can include GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
- Return type:
- get(ident, subfilters=None, fields=None, embeds=None, query=None, strict=True, head=False)[source]¶
Get the identified resource.
- Parameters:
ident – A value used to identify this resource. If the schema associated with this resource has multiple
id_keys, this value may be a list or tuple.subfilters (dict or None) – A dict of MQLAlchemy filters, with each key being the dot notation of the relationship they are to be applied to.
fields (list or None) – Names of fields to be included in the result.
embeds (collection or None) – A list of relationship and relationship field names to be included in the result.
query (
Select) – Optional base sqlalchemy query, allowing for sub-resource queries by using :meth:~`sqlalchemy.orm.with_parent`.strict (bool) – If
True, will raise an exception when bad parameters are passed. IfFalse, will quietly ignore any bad input and treat it as if none was provided.head (bool) – If this was a HEAD request. Doesn’t affect anything here, but supplied in case there’s desire to override the method.
- Raises:
ResourceNotFoundError – If no such resource exists.
BadRequestError – Invalid fields or embeds will result in a raised exception if strict is set to
True.MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
The resource itself if found.
- Return type:
- post(data)[source]¶
Create a new resource and store it in the db.
- Parameters:
data (dict) – Data used to create a new resource.
- Raises:
UnprocessableEntityError – If the supplied data cannot be processed.
MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
The created resource.
- Return type:
- put(ident, data)[source]¶
Replace the current object with the supplied one.
- Parameters:
- Raises:
ResourceNotFoundError – If no such resource exists.
UnprocessableEntityError – If the supplied data cannot be processed.
MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
The replaced resource.
- Return type:
- patch(ident, data)[source]¶
Update the identified resource with the supplied data.
- Parameters:
- Raises:
ResourceNotFoundError – If no such resource exists.
UnprocessableEntityError – If the supplied data cannot be processed.
MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
The updated resource.
- Return type:
- delete(ident)[source]¶
Delete the identified resource.
- Parameters:
ident – A value used to identify this resource. See
get()for more info.- Raises:
ResourceNotFoundError – If no such resource exists.
MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
None
- get_collection(filters=None, subfilters=None, fields=None, embeds=None, sorts=None, offset=None, limit=None, query=None, strict=True, head=False)[source]¶
Get a collection of resources.
- Parameters:
filters (dict or None) – MQLAlchemy filters to be applied on this query.
subfilters (dict or None) – A dict of MQLAlchemy filters, with each key being the dot notation of the relationship they are to be applied to.
fields (list or None) – Names of fields to be included in the result.
embeds (collection or None) – A list of relationship and relationship field names to be included in the result.
sorts (list of
SortInfo, or None) – Sorts to be applied to this query.offset (int or None) – Standard SQL offset to be applied to the query.
limit (int or None) – Standard SQL limit to be applied to the query.
query (
Select) – Optional base sqlalchemy query, allowing for sub-resource queries by using :meth:~`sqlalchemy.orm.with_parent`.strict (bool) – If
True, will raise an exception when bad parameters are passed. IfFalse, will quietly ignore any bad input and treat it as if none was provided.head (bool) – If this was a HEAD request. Doesn’t affect anything here, but supplied in case there’s desire to override the method.
- Raises:
BadRequestError – Invalid filters, sorts, fields, embeds, offset, or limit will result in a raised exception if strict is set to
True.MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
Resources meeting the supplied criteria.
- Return type:
- post_collection(data)[source]¶
Create multiple resources in the collection of resources.
- Parameters:
data (list) – List of resources to be created.
- Raises:
UnprocessableEntityError – If the supplied data cannot be processed.
MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
None
- put_collection(data)[source]¶
Raises an error since this method has no obvious use.
- Parameters:
data (list) – A list of object data. Would theoretically be used to replace the entire collection.
- Raises:
MethodNowAllowedError – When not overridden.
- patch_collection(data)[source]¶
Update a collection of resources.
Individual items may be updated accordingly as part of the request as well.
- Parameters:
data (list) – A list of object data. If the object contains a key
$opset to"add", the object will be added to the collection; otherwise the object must already be in the collection. If$opis set to"remove", it is accordingly removed from the collection.- Raises:
UnprocessableEntityError – If the supplied data cannot be processed.
MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
None
- delete_collection(filters=None, query=None, strict=True)[source]¶
Delete all filter matching members of the collection.
- Parameters:
- Raises:
UnprocessableEntityError – If the deletions are unable to be processed.
MethodNotAllowedError – If this method hasn’t been marked as allowed in the meta class options.
- Returns:
None
Model Converters¶
drowsy.converter¶
Convert SQLAlchemy models into Marshmallow schemas.
- class drowsy.convert.ModelResourceConverter(schema_cls: type[Schema] | None = None)[source]¶
Convert a model’s fields for use in a ModelResourceSchema.
- property2field(prop, instance=True, field_class=None, **kwargs)[source]¶
- Parameters:
prop (
ColumnPropertyorRelationshipProperty) – A column or relationship property used to determine a corresponding field.instance –
Trueif this method should return an actual instance of a field,Falseto return the actual field class.field_class (
Field) – Class of field to attempt to instantiate.kwargs – Keyword args to be used in the construction of the field.
- Returns:
Depending on the value of
instance, either a field or a field class.- Return type:
Fieldor type
- fields_for_model(model, *, include_fk=False, include_relationships=False, fields=None, exclude=None, base_fields=None, dict_cls=<class 'dict'>)[source]¶
Generate fields for the provided model.
- Parameters:
model – The SQLAlchemy model the generated fields correspond to.
include_fk (bool) –
Trueif fields should be generated for foreign keys,Falseotherwise.include_relationships (bool) –
Trueif relationship fields should be generated,Falseotherwise.fields (
Iterableor None) – A collection of field names to generate.exclude (
Iterableor None) – A collection of field names not to generate.base_fields (dict or None) – Optional dict of default fields to include in the result.
dict_cls – Optional specific type of dict to use for the result.
- Returns:
Generated fields corresponding to each model property.
- Return type:
dict or the provided dict_cls
Param Parsers¶
drowsy.parser¶
Functions for parsing query info from url parameters.
- class drowsy.parser.SortInfo(attr=None, direction='ASC')[source]¶
Used to transport info regarding sorts around.
- __init__(attr=None, direction='ASC')[source]¶
Instantiates a SortInfo object.
- Parameters:
- Raises:
ValueError – If
directionis not"ASC","DESC", orNone.TypeError – If any of the provided parameters are not of the specified type.
- class drowsy.parser.OffsetLimitInfo(offset=None, limit=None)[source]¶
Used to transport info regarding offsets and limits around.
- __init__(offset=None, limit=None)[source]¶
Instantiates a OffsetLimitInfo object.
- Parameters:
- Raises:
ValueError – If
offsetorlimitis not a positive number orNone.TypeError – If any of the provided parameters are not of the specified type.
- class drowsy.parser.SubfilterInfo(offset=None, limit=None, filters=None, sorts=None)[source]¶
Object used to transport info regarding subqueries around.
- __init__(offset=None, limit=None, filters=None, sorts=None)[source]¶
Instantiates a SubfilterInfo object.
- Parameters:
- Raises:
ValueError – If
offsetorlimitis not a positive number orNone.TypeError – If any of the provided parameters are not of the specified type.
- class drowsy.parser.QueryParamParser(query_params=None, error_messages=None, context=None)[source]¶
Utility class used to parse query parameters.
- __init__(query_params=None, error_messages=None, context=None)[source]¶
Sets up error messages, translations, and query params.
- Parameters:
query_params (dict or None) – Query params potentially containing filters, embeds, fields, and sorts.
error_messages (dict or None) – Optional dictionary of error messages, useful if you want to override the default errors.
context (dict, callable, or None) – Optional dictionary of context information. If error messages should be translated, context should include a
"gettext"key set to a callable that takes in a string and any kwargs and returns a translated string.
- make_error(key, **kwargs)[source]¶
Return an exception based on the
keyprovided.- Parameters:
key (str) – Failure type, used to choose an error message.
kwargs – Any additional arguments that may be used for generating an error message.
- Returns:
FilterParseError`in cases where there was an issue parsing a filter. `OffsetLimitParseError in cases where there was an issue parsing the offset, limit, or page value. ParseError raised in all other cases.
- parse_fields(fields_query_name='fields')[source]¶
Parse from query params the fields to include in the result.
- parse_offset_limit(page_max_size=None, page_query_name='page', offset_query_name='offset', limit_query_name='limit', strict=True)[source]¶
Parse offset and limit from the provided query params.
- Parameters:
page_max_size (int or None) – If page is provided,
page_max_sizelimits the number of results returned. Otherwise, if using limit and offset values from thequery_params,page_max_sizesets a max number of records to allow.page_query_name (str) – The name of the key used to check for a page value in the provided
query_params. If page is provided, it is used along with thepage_max_sizeto determine the offset that should be applied to the query. If a page number other than 1 is provided, apage_max_sizemust also be provided.offset_query_name (str) – The name of the key used to check for an offset value in the provided
query_params.limit_query_name (str) – The name of the key used to check for a limit value in the provided
query_params.strict – If
True, exceptions will be raised for invalid input. Otherwise, invalid input will be ignored.
- Raises:
OffsetLimitParseError – Applicable if using strict mode only. If the provided limit is greater than page_max_size, or an invalid page, offset, or limit value is provided, then an
OffsetLimitParseErroris raised.- Returns:
An offset and limit value for this query.
- Return type:
- class drowsy.parser.ModelQueryParamParser(query_params=None, error_messages=None, context=None)[source]¶
Param parser with added ability to parse MQLAlchemy filters.
- parse_subfilters(subquery_name='_subquery_', sublimit_name='_limit_', suboffset_name='_offset_', subsorts_name='_sorts_', strict=True)[source]¶
Parse nested resource subfilters, limits, offsets, and sorts.
Note that subquery parsing does limited checking on the validity of the subquery itself.
Given a query param “album.artist._subquery_.tracks.track_id” with value “5”, the resulting subfilters returned would be:
result = { "album.artist": SubfilterInfo( filters={ "$and": ["tracks.track_id": {"eq": 5}] } ) }
- Parameters:
subquery_name (str) – The name of the key used to check for a subquery value in the provided
query_params.sublimit_name (str) – The name of the key used to check for a sublimit value in the provided
query_params.suboffset_name (str) – The name of the key used to check for a suboffset value in the provided
query_params.subsorts_name (str) – The name of the key used to check for a subsorts value in the provided
query_params.strict (bool) – If
True, exceptions will be raised for invalid input. Otherwise, invalid input will be ignored.
- Raises:
FilterParseError – Malformed complex queries or invalid
query_paramswill result in anFilterParseErrorbeing raised ifstrictisTrue.OffsetLimitParseError – Raised in cases where there was an issue parsing an offset or limit if
strictisTrue.ParseError – Raised if
strictisTrueand there is an issue parsing the provided sorts for a subfilter.
- Returns:
A dictionary containing subqueries that can be passed to mqlalchemy for query filtering.
- Return type:
dict of str, SubfilterInfo
- parse_filters(model_class, complex_query_name='query', only_parse_complex=False, convert_key_names_func=<class 'str'>, subquery_name='_subquery_', sublimit_name='_limit_', suboffset_name='_offset_', subsorts_name='_sorts_', strict=True)[source]¶
Convert request params into MQLAlchemy friendly search.
- Parameters:
model_class – The SQLAlchemy class being queried.
complex_query_name (str) – The name of the key used to check for a complex query value in the provided
query_params. Note that the complex query should be a json dumped dictionary value.only_parse_complex (bool) – Set to
Trueif all simple filters in the query params should be ignored.convert_key_names_func (callable or None) – If provided, should take in a dot separated attr name and transform it such that the result is the corresponding dot separated attribute in the
model_classbeing queried. Useful if, for example, you want to allow users to provide an attr name in one format (say camelCase) and convert it to the naming format used for your model objects (likely underscore).subquery_name (str or None) – Query param name used to trigger a subquery. Query params that include this name will be ignored.
sublimit_name (str or None) – Query param name used to trigger a subquery resource limit. Query params that include this name will be ignored.
suboffset_name (str or None) – Query param name used to trigger a subquery resource offset. Query params that include this name will be ignored.
subsorts_name (str or None) – Query param name used to trigger a subquery sort. Query params that include this name will be ignored.
strict (bool) – If
True, exceptions will be raised for invalid input. Otherwise, invalid input will be ignored.
- Raises:
FilterParseError – Malformed complex queries or invalid
query_paramswill result in anFilterParseErrorbeing raised ifstrictisTrue.- Returns:
A dictionary containing filters that can be passed to mqlalchemy for query filtering.
- Return type:
Query Builders¶
drowsy.query_builder¶
Tools for building SQLAlchemy queries.
- drowsy.query_builder.manipulate_filters_to_list(filters)[source]¶
Return filters as a list of filters, regardless of input format.
- class drowsy.query_builder.QueryBuilder[source]¶
Utility class for building a SQLAlchemy query.
- row_number_supported(dialect, dialect_override=None)[source]¶
Given a SQL dialect, figure out if row_number is supported.
- apply_sorts(query, sorts, convert_key_names_func=<class 'str'>)[source]¶
Apply sorts to a provided query.
- Parameters:
query (
Query) – A SQLAlchemy query; filters must already have been applied.sorts (list of
SortInfo) – A list of sorts to apply to this query.convert_key_names_func (callable) – Used to convert key names. See
parse_filters().
- Raises:
AttributeError – If a sort with an invalid attr name is provided.
ValueError – If a sort not of type
SortInfois provided, or if query isn’t of a single model type.
- Returns:
A modified version of the provided query object.
- Return type:
Query
- apply_offset(query, offset)[source]¶
Applies offset and limit to the query if appropriate.
- Parameters:
query (
Query) – Any desired filters must already have been applied.offset (int or None) – Integer used to offset the query result.
- Raises:
ValueError – If a non
Noneoffset is provided that is converted to a negative integer.TypeError – If a non
Noneoffset is provided of a non integer, or integer convertible, type.
- Returns:
A modified query object with an offset applied.
- Return type:
Query
- apply_limit(query, limit)[source]¶
Applies limit to the query if appropriate.
- Parameters:
query (
Query) – Any desired filters must already have been applied.limit (int or None) – Integer used to limit the number of results returned.
- Raises:
ValueError – If a non
Nonelimit is provided that is converted to a negative integer.TypeError – If a non
Noneoffset is provided of a non integer, or integer convertible, type.
- Returns:
A modified query object with an limit applied.
- Return type:
Query
- apply_filters(model_class, query, filters, whitelist=None, nested_conditions=None, stack_size_limit=100, convert_key_names_func=<class 'str'>, gettext=None)[source]¶
Apply filters to a query using MQLAlchemy.
- Parameters:
query – A SQLAlchemy session or query.
model_class – The model having filters applied to it.
filters (dict or None) – The MQLAlchemy style filters to apply.
whitelist (callable, list, set, or None) – Used to determine what attributes are acceptable to be queried.
nested_conditions (callable, dict, or None) – Callable accepting one param, or dict, where the key/param is a dot separated relationship name, and the return value is any required SQL expressions for filtering that relationship.
stack_size_limit (int or None) – Used to limit the allowable complexity of the applied filters.
convert_key_names_func (callable) – Used to convert the attr names from user input (perhaps in camelCase) to the model format (likely in under_score format).
gettext (callable or None) – Used to translate any errors.
- Raises:
InvalidMQLException – Raised in cases where invalid filters were supplied.
- Returns:
The query with filters applied.
- class drowsy.query_builder.ModelResourceQueryBuilder[source]¶
Class for building a SQLAlchemy query by using resources.
- class SubqueryNode(name, alias=None, parent=None, children=None, subquery=None, limit=None, limit_source=None, offset=None, sorts=None, convert_key_name=None, whitelist=None, relationship_direction=None, joined=False, option=None, join=None, filters=None, id_keys=None, strategy=None, unaliased_filters=None)[source]¶
Used for building a query with subresource filters included.
Not intended for external access.
- __init__(name, alias=None, parent=None, children=None, subquery=None, limit=None, limit_source=None, offset=None, sorts=None, convert_key_name=None, whitelist=None, relationship_direction=None, joined=False, option=None, join=None, filters=None, id_keys=None, strategy=None, unaliased_filters=None)[source]¶
- Parameters:
name (str) – Name of the subresource.
alias
parent (SubqueryNode or None) – The parent of this SubqueryNode. Always has a value, unless this is the root node.
children (list of SubqueryNode or None) – Holds any child subresource nodes.
subquery – An aliased SQLAlchemy select statement.
limit (int or None) – Limit the number of results for this subresource.
limit_source (str) – Whether the limit was provided by the “user” or was a “default”.
offset (int or None) – Offset to apply to the query for this node.
sorts (list of
SortInfo) – Any sorts to apply to the query for this node.convert_key_name (callable or None) – Function for converting from user facing field names to internal field names.
whitelist (callable or None) – What fields are acceptable to be queried for this model.
joined (bool) –
Trueif the subquery has been joined into our final query.relationship_direction
option
- build(query, resource, filters, subfilters, embeds=None, offset=None, limit=None, sorts=None, strict=True, stack_size_limit=100, dialect_override=None)[source]¶
Build a complex query using user supplied parameters.
- Parameters:
query – A SQLAlchemy query.
resource (
BaseModelResource) – Base resource containing the sub resources that are to be filtered.filters (dict or None) – The MQLAlchemy style filters to apply.
subfilters (dict or None) – Dictionary of filters to apply to embedded subresources, with the subresource dot separated name as the key.
embeds (list or None) – List of subresources and fields to embed.
offset (int or None) – Integer used to offset the query result.
limit (int or None) – Integer used to limit the number of results returned.
sorts (list of
SortInfo) – A list of sorts to apply to this query.strict (bool) – If
True, will raise an exception when bad parameters are passed. IfFalse, will quietly ignore any bad input and treat it as if none was provided.stack_size_limit (int or None) – Used to limit the allowable complexity of the applied filters.
dialect_override (bool|None) –
Truewill build query with row_number support regardless of any db limitations. IfFalse, will avoid using row_number even if the database supports it. Mainly used for testing.
- Returns:
query with joins, load options, and subresource filters applied as appropriate.
- Raises:
BadRequestError – Uses the provided resource to raise an error when subfilters or embeds are unable to be successfully applied.
ValueError – Due to programmer error. Generally Only raised if one of the above parameters is of the wrong type.
- apply_subquery_loads(query, resource, subfilters, embeds=None, offset=None, limit=None, sorts=None, strict=True, stack_size_limit=100, dialect_override=None)[source]¶
Apply joins, load options, and subfilters to a query.
- Parameters:
query – A SQLAlchemy query.
resource (
BaseModelResource) – Base resource containing the sub resources that are to be filtered.subfilters – Dictionary of filters to apply to embedded subresources, with the subresource dot separated name as the key.
embeds (list or None) – List of subresources and fields to embed.
offset (int or None) – Integer used to offset the query result.
limit (int or None) – Integer used to limit the number of results returned.
sorts (list of
SortInfo) – A list of sorts to apply to this query.strict (bool) – If
True, will raise an exception when bad parameters are passed. IfFalse, will quietly ignore any bad input and treat it as if none was provided.stack_size_limit (int or None) – Used to limit the allowable complexity of the applied filters.
dialect_override (bool|None) –
Truewill build query with row_number support regardless of any db limitations. IfFalse, will avoid using row_number even if the database supports it. Mainly used for testing.
- Returns:
query with joins, load options, and subresource filters applied as appropriate.
- Return type:
Query- Raises:
BadRequestError – Uses the provided resource to raise an error when subfilters or embeds are unable to be successfully applied.
ValueError – Due to programmer error. Generally Only raised if one of the above parameters is of the wrong type.
Fields¶
drowsy.fields¶
Marshmallow fields used in resource schemas.
- class drowsy.fields.EmbeddableRelationshipMixin(*args, **kwargs)[source]¶
Defaults to returning a relationship’s URL if not embedded.
- class drowsy.fields.NestedRelated(nested, load_default=<marshmallow.missing>, dump_default=<marshmallow.missing>, exclude=(), only=None, many=False, columns=None, permissions_cls=None, **kwargs)[source]¶
A nested relationship field for use in ModelResourceSchema.
- __init__(nested, load_default=<marshmallow.missing>, dump_default=<marshmallow.missing>, exclude=(), only=None, many=False, columns=None, permissions_cls=None, **kwargs)[source]¶
Initialize a nested related field.
- Parameters:
nested – The Schema class or class name (string) to nest, or
"self"to nest aSchemawithin itself.default – Default value to use if attribute is missing.
only (tuple, str, or None) – A tuple or string of the field(s) to marshal. If
None, all fields will be marshalled. If a field name (string) is given, only a single value will be returned as output instead of a dictionary. This parameter takes precedence overexclude.many (bool) – Whether the field is a collection of objects.
columns (list) – Optional column names on related model. If not provided, the primary key(s) of the related model will be used.
permissions_cls – The class of permissions to apply to this relationship. Defaults to allowing all relationship operation. May be used to limit the operations that can be done.
kwargs – The same keyword arguments that
Fieldreceives.
- property model¶
The model associated with this relationship.
Gets a list of id keys associated with this nested obj.
Note the hierarchy of id keys to return:
If the attached schema for this nested field has an id_keys attr, use those keys.
Else, if this field had a columns arg passed when initialized, use those column names.
Else, use the primary key columns.
- property context¶
The context dictionary for the parent
Schema.
- class drowsy.fields.Relationship(*args, **kwargs)[source]¶
Default relationship field.
When serialized, returns the relationship’s assumed URL if not embedded. Otherwise, returns the nested values of the relationship.
- class drowsy.fields.APIUrl(endpoint_name, base_url=None, *args, **kwargs)[source]¶
Text field, displays the url of the resource it’s attached to.
- __init__(endpoint_name, base_url=None, *args, **kwargs)[source]¶
Initializes an APIUrl field.
- Parameters:
endpoint_name (str) – The name of this URL endpoint and where to access this resource.
base_url (str or callable) – A str or callable (with no args) that returns the base part of the API url: https://example.com/api
args – Any field arguments to be passed to the super constructor.
kwargs – Any field keyword arguments to be passed to the super constructor.
- serialize(attr, obj, accessor=None, **kwargs)[source]¶
Serialize an API url.
- Parameters:
attr (str) – The attribute name of this field. Unused.
obj – The object to pull any needed info from.
accessor (callable or None) – Function used to pull values from
obj. Defaults toget_value().
- Raises:
ValidationError – In case of formatting problem.
- Returns:
The serialized API url value.
Routers¶
drowsy.router¶
Tools for automatically routing API url paths to resources.
- class drowsy.router.ResourceRouterABC(resource, error_messages=None)[source]¶
Abstract base class for a resource based automatic router.
- __init__(resource, error_messages=None)[source]¶
Sets up router error messages and translations.
- Parameters:
resource (
Resource) – A resource instance.error_messages (dict or None) – Optional dictionary of error messages, useful if you want to override the default errors.
- property context¶
Return the context used for this request.
- make_error(key, **kwargs)[source]¶
Returns an exception based on the
keyprovided.- Parameters:
key (str) – Failure type, used to choose an error message.
kwargs – Any additional arguments that may be used for generating an error message.
- Returns:
ResourceNotFoundError, MethodNotAllowedError, or defaults to BadRequestError.
- options(path)[source]¶
Get a list of available options for this resource.
- Returns:
The options available for this resource at the supplied
path.- Return type:
- get(path, query_params=None, strict=True, head=False)[source]¶
Generic API router for GET requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.query_params (dict or None) – Dictionary of query parameters, likely provided as part of a request. Defaults to an empty dict.
strict (bool) – If
True, bad query params will raise non fatal errors rather than ignoring them.head (bool) –
Trueif this was a HEAD request.
- Returns:
If this is a single entity query, an individual resource in dict form. If this is a collection query, a list of resources in dict form.
- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
BadRequestError – Invalid filters, sorts, fields, embeds, offset, or limit as defined in the provided query params will result in a raised exception if strict is set to
True.
- put(path, data)[source]¶
Generic API router for PUT requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.data – A dict or list of dicts of entities to replace the current value with at the given path.
- Returns:
If this is a put to a subresource collection, the replaced subresource is returned. If this is a put to an individual resource then the replaced resource is returned. If this is a put to a field, the replaced field value is returned.
- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
MethodNotAllowedError – A put on a top level collection will raise this error.
- patch(path, data)[source]¶
Generic API router for PATCH requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.data – A dict or list of dicts of entities to add or remove at the given path.
- Returns:
If this is a patch to a resource collection,
Noneis returned. If this is a patch to a subresource collection, the updated subresource is returned. If this is a patch to an individual resource then the updated resource is returned. If this is a patch to a field, the updated field value is returned.- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
MethodNotAllowedError – A patch at a valid path may return this due to permission issues.
- post(path, data)[source]¶
Generic API router for POST requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.data – A dict or list of dicts of new entities to add at the given path.
- Returns:
If this is a post to a top level resource, then the newly created resource or list of resources will be returned in dict or list of dicts form. If this is a post to a subresource, then the updated subresource data will be returned.
- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
MethodNotAllowedError – Posts to individual properties or resources will cause an error.
- delete(path, query_params=None)[source]¶
Generic API router for DELETE requests.
- Parameters:
- Returns:
Noneif successful.- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
BadRequestError – Invalid filters, sorts, fields, embeds, offset, or limit as defined in the provided query params will result in a raised exception if strict is set to
True.MethodNotAllowedError – If deleting the resource at the supplied path is not allowed.
- dispatcher(method, path, query_params=None, data=None, strict=True)[source]¶
Route requests based on path and resource.
- Parameters:
method (str) – HTTP verb method used to make this request.
path (str) – The resource path specified. This should not include the root
/apior any versioning info.query_params (dict) – Dictionary of query parameters, likely provided as part of a request.
strict (bool) – If
True, faulty pagination info, fields, or embeds will result in an error being raised rather than silently ignoring them.data – The data supplied as part of the incoming request body. Optional, and the format of this data may vary.
- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
BadRequestError – Invalid filters, sorts, fields, embeds, offset, or limit as defined in the provided query params will result in a raised exception if strict is set to
True.UnprocessableEntityError – On post, patch, put, and delete requests, if the corresponding action can not be completed, an exception will be raised.
- Returns:
Dependent on the method and whether the path refers to a collection or individual resource.
Get: An individual resource in dict form.
- Head: An individual resource in dict form. Should only
be used for header info, the actual resource should not be returned to a user.
Post: The created resource in dict form if successful.
Patch: The updated resource in dict form if successful.
Put: The replaced resource in dict form if successful.
Delete:
Noneif successful.Get collection: A list of resources in dict form.
- Head collection: A list of resources in dict form. Should
only be used for header info, the actual resource should not be returned to a user.
Patch collection:
Noneif successful.Post collection: A list of created resources in dict form.
Delete collection:
Noneif successful.
- class drowsy.router.ModelResourceRouter(resource=None, error_messages=None, context=None, session=None, convert_type_func=None)[source]¶
Utility class used to route incoming requests.
Currently handles nested resources assuming they’re of
ModelResourcetype.- __init__(resource=None, error_messages=None, context=None, session=None, convert_type_func=None)[source]¶
Sets up router error messages and translations.
- Parameters:
resource (
ModelResourceor None) – A resource instance. If none is provided, an attempt to dynamically create a resource upon dispatch using the provided path, context, and session will be made.error_messages (dict or None) – Optional dictionary of error messages, useful if you want to override the default errors.
convert_type_func (callable|None) – Function with two args, the first being a string value, and the second a SQLAlchemy column type to convert that value to. If no value is provided, defaults to using
convert_to_alchemy_typefromMQLAlchemy.
- property context¶
Return the schema context for this resource.
- property session¶
Return the session for this resource.
- put(path, data)[source]¶
Generic API router for PUT requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.data – A dict or list of dicts of entities to replace the current value with at the given path.
- Returns:
If this is a put to a subresource collection, the replaced subresource is returned. If this is a put to an individual resource then the replaced resource is returned. If this is a put to a field, the replaced field value is returned.
- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
MethodNotAllowedError – A put on a top level collection will raise this error.
- patch(path, data)[source]¶
Generic API router for PATCH requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.data – A dict or list of dicts of entities to add or remove at the given path.
- Returns:
If this is a patch to a resource collection,
Noneis returned. If this is a patch to a subresource collection, the updated subresource is returned. If this is a patch to an individual resource then the updated resource is returned. If this is a patch to a field, the updated field value is returned.- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
MethodNotAllowedError – A patch at a valid path may return this due to permission issues.
- post(path, data)[source]¶
Generic API router for POST requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.data – A dict or list of dicts of new entities to add at the given path.
- Returns:
If this is a post to a top level resource, then the newly created resource or list of resources will be returned in dict or list of dicts form. If this is a post to a subresource, then the updated subresource data will be returned.
- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
MethodNotAllowedError – Posts to individual properties or resources will cause an error.
- options(path)[source]¶
Generic API router for OPTIONS requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.- Returns:
A list of available options for the resource at the supplied
path. Such options may include GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
- get(path, query_params=None, strict=True, head=False)[source]¶
Generic API router for GET requests.
- Parameters:
path (str) – The resource path specified. This should not include the root
/apior any versioning info.query_params (dict or None) – Dictionary of query parameters, likely provided as part of a request. Defaults to an empty dict.
strict (bool) – If
True, bad query params will raise non fatal errors rather than ignoring them.head (bool) –
Trueif this was a HEAD request.
- Returns:
If this is a single entity query, an individual resource or
None. If this is a collection query, a list of resources. If it’s an instance field query, the raw field value.- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
BadRequestError – Invalid filters, sorts, fields, embeds, offset, or limit as defined in the provided query params will result in a raised exception if strict is set to
True.
- delete(path, query_params=None)[source]¶
Generic API router for DELETE requests.
- Parameters:
- Returns:
Noneif successful.- Raises:
ResourceNotFoundError – If no resource can be found at the provided path.
BadRequestError – Invalid filters, sorts, fields, embeds, offset, or limit as defined in the provided query params will result in a raised exception if strict is set to
True.MethodNotAllowedError – If deleting the resource at the supplied path is not allowed.
Permissions¶
drowsy.permissions¶
Classes for building permissions into an API.
- class drowsy.permissions.OpPermissionsABC(**kwargs)[source]¶
Inherit from this class to implement permissions logic.
- check(operation, obj_data, instance=None, context=None, field=None, **kwargs)[source]¶
Check if the given action is allowed.
- Parameters:
operation (str) – Action type. Options include
"add","remove","create", and"replace” for collections, and"set"may be used as an alias for"add"in single object nested situations. Any actions that are part of custom defined field types will also need to be handled.obj_data – The user supplied data. Likely a dictionary for a child object.
instance – An unmodified instance of the object with data yet to be loaded into it.
context – The context of the current action. May include info such as the current user.
field – The Marshmallow field that triggered the permission check.
kwargs – Any additional arguments that may be used for checking permissions.
- Returns:
Trueif no error is raised.- Return type:
- class drowsy.permissions.AllowAllOpPermissions(**kwargs)[source]¶
Allows any and all actions on a relationship.
- check(operation, obj_data, instance=None, context=None, field=None, **kwargs)[source]¶
Check if the given action is allowed.
Always returns
True.- Parameters:
operation (str) – Action type. Options include
"add","remove","create", and"replace” for collections, and"set"may be used as an alias for"add"in single object nested situations. Any actions that are part of custom defined field types will also need to be handled.obj_data – The user supplied data. Likely a dictionary for a child object.
instance – An unmodified instance of the object with data yet to be loaded into it.
context – The context of the current action. May include info such as the current user.
field – The Marshmallow field that triggered the permission check.
kwargs – Any additional arguments that may be used for checking permissions.
- Returns:
Trueif no error is raised.- Return type:
- class drowsy.permissions.DisallowAllOpPermissions(**kwargs)[source]¶
Disallows any and all actions on a relationship.
- check(operation, obj_data, instance=None, context=None, field=None, **kwargs)[source]¶
Check if the given action is allowed.
Always returns
False.- Parameters:
operation (str) – Action type. Options include
"add","remove","create", and"replace” for collections, and"set"may be used as an alias for"add"in single object nested situations. Any actions that are part of custom defined field types will also need to be handled.obj_data – The user supplied data. Likely a dictionary for a child object.
instance – An unmodified instance of the object with data yet to be loaded into it.
context – The context of the current action. May include info such as the current user.
field – The Marshmallow field that triggered the permission check.
kwargs – Any additional arguments that may be used for checking permissions.
- Returns:
Trueif no error is raised.- Return type:
Resource Class Registry¶
Enables a registry of
Resource classes.
This allows for string lookup of resources, making it easier to reference them dynamically and avoid circular dependencies.
Warning
This module is treated as private API. Users should not need to use this module directly.
This module was taken directly from Marshmallow. The only core difference is that it serves as a registry of resources rather than schemas. Please see below for the appropriate Marshmallow attribution.
Copyright 2015 Steven Loria
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- drowsy.resource_class_registry.register(classname, cls)[source]¶
Add a class to the registry of resource classes.
When a class is registered, an entry for both its class name and its full, module-qualified path are added to the registry.
Example:
class MyClass: pass register('MyClass', MyClass) # Registry: # { # 'MyClass': [path.to.MyClass], # 'path.to.MyClass': [path.to.MyClass], # }
- Parameters:
classname (str) – Name of the class to be registered.
cls – The class to be registered.
- drowsy.resource_class_registry.get_class(classname, all=False)[source]¶
Retrieve a class from the registry.
- Parameters:
- Raise:
RegistryErrorif the class cannot be found or if there are multiple entries for the given class name andallis notTrue.- Returns:
The class matching the name provided if previously registered, or potentially a list of classes if
allisTrue.
Utilities¶
drowsy.utils¶
Utility functions for Drowsy.
- drowsy.utils.get_error_message(error_messages, key, gettext=None, **kwargs)[source]¶
Get an error message based on a key name.
If the error message is a callable, kwargs are passed to that callable.
Assuming the resulting error message is a string,
self.gettextwill be passed that string along with any kwargs to potentially translate and fill in any template variables.- Parameters:
error_messages (dict) – A dictionary of string or callable errors mapped to key names.
key (str) – Key used to access the error messages dict.
gettext (callable or None) – Optional callable that may be used to translate any error messages.
kwargs (dict) – Any additional arguments that may be passed to a callable error message, or used to translate and/or format an error message string.
- Raises:
KeyError – If the
error_messagesdict does not contain the providedkey.- Returns:
An error message with the supplied kwargs injected.
- Return type:
- drowsy.utils.get_field_by_data_key(schema, data_key)[source]¶
Helper method to get a field from schema by data_key name.
- Parameters:
schema (
Schema) – Instantiated schema.data_key (str) – Name as the field as it was serialized.
- Returns:
The schema field if found, None otherwise.
- Return type:
Fieldor None
Exceptions¶
drowsy.exc¶
Exceptions for Drowsy.
- exception drowsy.exc.DrowsyError(code, message, **kwargs)[source]¶
Exception that contains a simple message attribute.
- exception drowsy.exc.UnprocessableEntityError(code, message, errors, **kwargs)[source]¶
Exception for when provided data is unable to be deserialized.
- exception drowsy.exc.PermissionDeniedError(code, message, errors, **kwargs)[source]¶
Exception for when provided data is unable to be deserialized.
- exception drowsy.exc.BadRequestError(code, message, **kwargs)[source]¶
Exception for when a request is unable to be processed.
- exception drowsy.exc.MethodNotAllowedError(code, message, **kwargs)[source]¶
Error for when a request is made with an unsupported method.
- exception drowsy.exc.ResourceNotFoundError(code, message, **kwargs)[source]¶
Exception for when a requested resource cannot be found.
- exception drowsy.exc.ParseError(code, message, **kwargs)[source]¶
Generic exception class for parsing errors.
- exception drowsy.exc.OffsetLimitParseError(code, message, **kwargs)[source]¶
Generic exception class for offset or limit parsing errors.
- exception drowsy.exc.FilterParseError(code, message, **kwargs)[source]¶
Generic exception class for filter parsing errors.
- exception drowsy.exc.PermissionValidationError(message: str | list | dict, field_name: str = '_schema', data: Mapping[str, Any] | Iterable[Mapping[str, Any]] | None = None, valid_data: list[Any] | dict[str, Any] | None = None, **kwargs)[source]¶
Generic schema exception class for an unauthorized action.