Resources API

This library allows to easily create RESTful APIs to various databases as resources in a Falcon application.

Supported backends include SQL (SQLAlchemy) and NoSQL (MongoDB, ElasticSearch) databases.

Typical usage include:

exception api.exceptions.ApiException[source]

Base class for all API exceptions.

exception api.exceptions.ParamException[source]

Should be raised in custom clean methods when value is invalid.

Collection and single resource classes implementing serializers and query builders to use a common request and response format even when using different database engines.

class api.resources.elasticsearch.CollectionResource(objects_class, connection, max_limit=None)[source]

Allows to fetch a collection of a resource (GET) and to create new resource in that collection (POST). May be extended to allow batch operations (ex. PATCH). When fetching a collection (GET), following params are supported:

  • limit, offset - for pagination
  • total_count - to calculate total number of items matching filters, without pagination
  • all other params are treated as filters, syntax mimics Django filters, see ElasticSearchMixin._underscore_operators
AGGR_GROUPBY = 'group_by'
AGGR_GROUPLIMIT = 'group_limit'
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
PARAM_LIMIT = 'limit'
PARAM_OFFSET = 'offset'
PARAM_ORDER = 'order'
PARAM_TEXT_QUERY = 'q'
PARAM_TOTALS = 'totals'
PARAM_TOTAL_COUNT = 'total_count'
clean(data)

Called after deserialize(), might perform more complex data filtering and validation.

Parameters:data (dict) –
Returns:a tuple of data and errors after additional cleanup
create(req, resp, data)[source]
deserialize(data)

Converts an external representation to values that can be assigned to an instance of objects_class.

Parameters:data (dict) – a dictionary
Returns:a dictionary with converted values
Return type:dict
filter_by(query, conditions, order_criteria=None)
Parameters:
  • query (elasticsearch.Search) – Search object
  • conditions (dict) – conditions dictionary
  • order_criteria (list) – optional order criteria
Returns:

modified query

Return type:

elasticsearch.Search

classmethod flatten_aggregate(key, value)[source]
get_base_query(req, resp)[source]
get_data(req, resp)[source]
get_match_query(value, default_op, boost=1)
get_object_list(queryset, limit=None, offset=None)

Return a list of objects returned from a query.

Parameters:
  • queryset – queryset from get_queryset()
  • limit (int) – number of elements to return, max_limit will be used if None
  • offset (int) – slice list of element at the beginning
Returns:

sliced results based on limit and offset

get_param_or_post(req, name, default=None, pop_params=True)

Gets specified param from request params or body. If found in params, it’s removed.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • name (str) – param name
  • default – Default value
  • pop_params (bool) – if True, will pop from req params
Returns:

param extracted from query params or request body

get_param_totals(req)

Gets the totals and total_count params and normalizes them into a single list.

Parameters:req (falcon.request.Request) – Falcon request
Returns:total expressions
Return type:list
get_queryset(req, resp)[source]
get_schema(objects_class)

Gets a JSON Schema (http://json-schema.org) for current objects class.

Parameters:objects_class – class represent single element of object lists that suppose to be returned
Returns:a JSON Schema
Return type:dict
get_special_params()[source]
get_total_objects(queryset, totals)[source]
on_get(req, resp)[source]
on_head(req, resp)[source]
on_options(req, resp, **kwargs)

Returns allowed methods in the Allow HTTP header. Also returns a JSON Schema, if supported by current resource.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_post(req, resp, *args, **kwargs)

Add (create) a new record to the collection.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_put(req, resp, *args, **kwargs)

Add (create) a new record to the collection.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
render_response(result, req, resp, status='200 OK')
Parameters:
  • result – Data to be returned in the response
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • status (str) – HTTP status code
serialize(obj)
serialize_column(value)
class api.resources.elasticsearch.ElasticSearchMixin[source]
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
filter_by(query, conditions, order_criteria=None)[source]
Parameters:
  • query (elasticsearch.Search) – Search object
  • conditions (dict) – conditions dictionary
  • order_criteria (list) – optional order criteria
Returns:

modified query

Return type:

elasticsearch.Search

classmethod get_match_query(value, default_op, boost=1)[source]
serialize(obj)[source]
classmethod serialize_column(value)[source]
class api.resources.elasticsearch.SingleResource(objects_class, connection)[source]

Allows to fetch a single resource (GET) and to update (PATCH, PUT) or remove it (DELETE). When fetching a resource (GET).

DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
clean(data)

Called after deserialize(), might perform more complex data filtering and validation.

Parameters:data (dict) –
Returns:a tuple of data and errors after additional cleanup
delete(req, resp, obj)[source]
deserialize(data)

Converts an external representation to values that can be assigned to an instance of objects_class.

Parameters:data (dict) – a dictionary
Returns:a dictionary with converted values
Return type:dict
filter_by(query, conditions, order_criteria=None)
Parameters:
  • query (elasticsearch.Search) – Search object
  • conditions (dict) – conditions dictionary
  • order_criteria (list) – optional order criteria
Returns:

modified query

Return type:

elasticsearch.Search

get_match_query(value, default_op, boost=1)
get_object(req, resp, path_params, for_update=False)[source]
get_param_or_post(req, name, default=None, pop_params=True)

Gets specified param from request params or body. If found in params, it’s removed.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • name (str) – param name
  • default – Default value
  • pop_params (bool) – if True, will pop from req params
Returns:

param extracted from query params or request body

get_schema(objects_class)

Gets a JSON Schema (http://json-schema.org) for current objects class.

Parameters:objects_class – class represent single element of object lists that suppose to be returned
Returns:a JSON Schema
Return type:dict
on_delete(req, resp, *args, **kwargs)

Deletes a single record.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_get(req, resp, *args, **kwargs)

Gets a single record.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_head(req, resp, *args, **kwargs)
Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_options(req, resp, **kwargs)

Returns allowed methods in the Allow HTTP header. Also returns a JSON Schema, if supported by current resource.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_patch(req, resp, *args, **kwargs)

Updates a single record. Changes only specified fields.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_put(req, resp, *args, **kwargs)

Updates a single record. This should set all missing fields to default values, but we’re not going to be so strict.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
render_response(result, req, resp, status='200 OK')
Parameters:
  • result – Data to be returned in the response
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • status (str) – HTTP status code
serialize(obj)
serialize_column(value)
update(req, resp, data, obj)[source]
class api.resources.mongoengine.CollectionResource(objects_class, max_limit=None)[source]
AGGR_GROUPBY = 'group_by'
AGGR_GROUPLIMIT = 'group_limit'
PARAM_LIMIT = 'limit'
PARAM_OFFSET = 'offset'
PARAM_ORDER = 'order'
PARAM_TEXT_QUERY = 'q'
PARAM_TOTALS = 'totals'
PARAM_TOTAL_COUNT = 'total_count'
clean(data)

Called after deserialize(), might perform more complex data filtering and validation.

Parameters:data (dict) –
Returns:a tuple of data and errors after additional cleanup
create(req, resp, data)[source]
deserialize(data)

Converts an external representation to values that can be assigned to an instance of objects_class.

Parameters:data (dict) – a dictionary
Returns:a dictionary with converted values
Return type:dict
get_data(req, resp)
Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
get_object_list(queryset, limit=None, offset=None)

Return a list of objects returned from a query.

Parameters:
  • queryset – queryset from get_queryset()
  • limit (int) – number of elements to return, max_limit will be used if None
  • offset (int) – slice list of element at the beginning
Returns:

sliced results based on limit and offset

get_param_or_post(req, name, default=None, pop_params=True)

Gets specified param from request params or body. If found in params, it’s removed.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • name (str) – param name
  • default – Default value
  • pop_params (bool) – if True, will pop from req params
Returns:

param extracted from query params or request body

get_param_totals(req)

Gets the totals and total_count params and normalizes them into a single list.

Parameters:req (falcon.request.Request) – Falcon request
Returns:total expressions
Return type:list
get_queryset(req, resp)[source]
get_schema(objects_class)

Gets a JSON Schema (http://json-schema.org) for current objects class.

Parameters:objects_class – class represent single element of object lists that suppose to be returned
Returns:a JSON Schema
Return type:dict
get_total_objects(queryset, totals)

Return total number of results in a query.

Parameters:
  • queryset – queryset object from get_queryset()
  • totals (list) – a list of dicts with aggregate function as key and column as value
Returns:

dict with totals calculated in this query, ex. total_count with number of results

Return type:

dict

on_get(req, resp)

Gets a list of records.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_head(req, resp)
Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_options(req, resp, **kwargs)

Returns allowed methods in the Allow HTTP header. Also returns a JSON Schema, if supported by current resource.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_post(req, resp, *args, **kwargs)

Add (create) a new record to the collection.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_put(req, resp, *args, **kwargs)

Add (create) a new record to the collection.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
render_response(result, req, resp, status='200 OK')
Parameters:
  • result – Data to be returned in the response
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • status (str) – HTTP status code
serialize(obj)

Converts the object to an external representation. If the object is serializable, no conversion is necessary.

Parameters:obj – single instance of objects_class
Returns:python json serializable object like dicts / lists / strings / ints and so on...

Example:

return {'id': obj.id, 'name': obj.name}
class api.resources.mongoengine.SingleResource(objects_class)[source]
clean(data)

Called after deserialize(), might perform more complex data filtering and validation.

Parameters:data (dict) –
Returns:a tuple of data and errors after additional cleanup
delete(req, resp, obj)

Delete an existing record. :param req: Falcon request :type req: falcon.request.Request

Parameters:
  • resp (falcon.response.Response) – Falcon response
  • obj – the object to delete
deserialize(data)

Converts an external representation to values that can be assigned to an instance of objects_class.

Parameters:data (dict) – a dictionary
Returns:a dictionary with converted values
Return type:dict
get_object(req, resp, path_params, for_update=False)[source]
get_param_or_post(req, name, default=None, pop_params=True)

Gets specified param from request params or body. If found in params, it’s removed.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • name (str) – param name
  • default – Default value
  • pop_params (bool) – if True, will pop from req params
Returns:

param extracted from query params or request body

get_schema(objects_class)

Gets a JSON Schema (http://json-schema.org) for current objects class.

Parameters:objects_class – class represent single element of object lists that suppose to be returned
Returns:a JSON Schema
Return type:dict
on_delete(req, resp, *args, **kwargs)

Deletes a single record.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_get(req, resp, *args, **kwargs)

Gets a single record.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_head(req, resp, *args, **kwargs)
Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_options(req, resp, **kwargs)

Returns allowed methods in the Allow HTTP header. Also returns a JSON Schema, if supported by current resource.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_patch(req, resp, *args, **kwargs)

Updates a single record. Changes only specified fields.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_put(req, resp, *args, **kwargs)

Updates a single record. This should set all missing fields to default values, but we’re not going to be so strict.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
render_response(result, req, resp, status='200 OK')
Parameters:
  • result – Data to be returned in the response
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • status (str) – HTTP status code
serialize(obj)

Converts the object to an external representation. If the object is serializable, no conversion is necessary.

Parameters:obj – single instance of objects_class
Returns:python json serializable object like dicts / lists / strings / ints and so on...

Example:

return {'id': obj.id, 'name': obj.name}
update(req, resp, data, obj)[source]
class api.resources.sqlalchemy.AlchemyMixin[source]

Provides serialize and deserialize methods to convert between JSON and SQLAlchemy datatypes.

DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
IGNORE_UNKNOWN_FILTER = False
MULTIVALUE_SEPARATOR = ','
PARAM_RELATIONS = 'relations'
PARAM_RELATIONS_ALL = '_all'
RELATIONS_AS_LIST = True
clean_relations(relations)[source]

Checks all special values in relations and makes sure to always return either a list or None.

Parameters:relations (str | list) – relation names
Returns:either a list (may be empty) or None if all relations should be included
Return type:list[str] | None
deserialize(data, mapper=None)[source]

Converts incoming data to internal types. Detects relation objects. Moves one to one relation attributes to a separate key. Silently skips unknown attributes.

Parameters:
  • data (dict) – incoming data
  • mapper (sqlalchemy.orm.mapper.Mapper) – mapper, if None, mapper of the main object class will be used
Returns:

data with correct types

Return type:

dict

deserialize_column(column, value)[source]
deserialize_onetoone(mapper, key, value)[source]
deserialize_relation(rel_mapper, value)[source]
exclude_by(query, conditions)[source]
Parameters:
  • query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
  • conditions (dict) – conditions dictionary
Returns:

modified query

Return type:

sqlalchemy.orm.query.Query

filter_by(query, conditions, order_criteria=None)[source]
Parameters:
  • query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
  • conditions (dict) – conditions dictionary
  • order_criteria (dict) – optional order criteria
Returns:

modified query

Return type:

sqlalchemy.orm.query.Query

static get_default_schema(model_class, method='POST')[source]

Returns a schema to be used in falconjsonio.schema.request_schema decorator :return:

static get_or_create(db_session, model_class, query_attrs, update_attrs=None, update_existing=False)[source]

Fetches the record and if it doesn’t exist yet, creates it, handling a race condition.

Parameters:
  • db_session (sqlalchemy.orm.session.Session) – session within DB connection
  • model_class (class) – class of the model to return or create
  • query_attrs (dict) – attributes used to fetch the model
  • update_attrs (dict) – attributes used to create a new model
  • update_existing (bool) – if True and update_attrs are set, updates existing records
Returns:

existing or new object and a flag if existing or new object is being returned

Return type:

tuple

get_schema[source]
static get_tsquery(value, default_op)[source]
static next_alias(aliases, name, obj_class, use_existing=True, prefix='')[source]
order_by(query, criteria)[source]
Parameters:query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
Returns:modified query
Return type:sqlalchemy.orm.query.Query
classmethod save_resource(obj, data, db_session)[source]

Extracts relation dicts from data, saves them and then updates the main object.

Parameters:
  • obj (object) – a new or existing model
  • data (dict) – data to assign to the model and/or its relations
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
classmethod save_resource_relations(obj, data, db_session)[source]
classmethod serialize(obj, skip_primary_key=False, skip_foreign_keys=False, relations_level=1, relations_ignore=None, relations_include=None)[source]

Converts the object to a serializable dictionary. :param obj: the object to serialize

Parameters:
  • skip_primary_key (bool) – should primary keys be skipped
  • skip_foreign_keys (bool) – should foreign keys be skipped
  • relations_level (int) – how many levels of relations to serialize
  • relations_ignore (list) – relationship names to ignore
  • relations_include (list) – relationship names to include
Returns:

a serializable dictionary

Return type:

dict

classmethod serialize_column(column, value)[source]
classmethod serialize_columns(obj, data, skip_primary_key=False, skip_foreign_keys=False)[source]
classmethod serialize_relations(obj, data, relations_level=1, relations_ignore=None, relations_include=None)[source]
classmethod session_scope(db_engine=None, session_class=None)[source]

Provide a scoped db session for a series of operarions. The session is created immediately before the scope begins, and is closed on scope exit. :param db_engine: SQLAlchemy Engine or other Connectable :type db_engine: sqlalchemy.engine.Connectable

Parameters:session_class (sqlalchemy.orm.Session) – SQLAlchemy Session
classmethod update_or_create(db_session, mapper, attributes)[source]

Updated the record if attributes contain the primary key value(s) and creates it if they don’t.

Parameters:
  • db_session (sqlalchemy.orm.session.Session) –
  • mapper (sqlalchemy.orm.mapper.Mapper) –
  • attributes (dict) –
Returns:

Return type:

object

class api.resources.sqlalchemy.CollectionResource(objects_class, db_engine, max_limit=None, eager_limit=None)[source]

Allows to fetch a collection of a resource (GET) and to create new resource in that collection (POST). May be extended to allow batch operations (ex. PATCH). When fetching a collection (GET), following params are supported: * limit, offset - for pagination * total_count - to calculate total number of items matching filters, without pagination * relations - list of relation names to include in the result, uses special value _all for all relations * all other params are treated as filters, syntax mimics Django filters, see AlchemyMixin._underscore_operators User input can be validated by attaching the falconjsonio.schema.request_schema() decorator.

AGGR_GROUPBY = 'group_by'
AGGR_GROUPLIMIT = 'group_limit'
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
IGNORE_UNKNOWN_FILTER = False
MULTIVALUE_SEPARATOR = ','
PARAM_LIMIT = 'limit'
PARAM_OFFSET = 'offset'
PARAM_ORDER = 'order'
PARAM_RELATIONS = 'relations'
PARAM_RELATIONS_ALL = '_all'
PARAM_TEXT_QUERY = 'q'
PARAM_TOTALS = 'totals'
PARAM_TOTAL_COUNT = 'total_count'
RELATIONS_AS_LIST = True
VIOLATION_UNIQUE = '23505'
clean(data)

Called after deserialize(), might perform more complex data filtering and validation.

Parameters:data (dict) –
Returns:a tuple of data and errors after additional cleanup
clean_relations(relations)

Checks all special values in relations and makes sure to always return either a list or None.

Parameters:relations (str | list) – relation names
Returns:either a list (may be empty) or None if all relations should be included
Return type:list[str] | None
create(req, resp, data, db_session=None)[source]

Create a new or update an existing record using provided data. :param req: Falcon request :type req: falcon.request.Request

Parameters:
  • resp (falcon.response.Response) – Falcon response
  • data (dict) –
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
Returns:

created object, serialized to a dict

Return type:

dict

deserialize(data, mapper=None)

Converts incoming data to internal types. Detects relation objects. Moves one to one relation attributes to a separate key. Silently skips unknown attributes.

Parameters:
  • data (dict) – incoming data
  • mapper (sqlalchemy.orm.mapper.Mapper) – mapper, if None, mapper of the main object class will be used
Returns:

data with correct types

Return type:

dict

deserialize_column(column, value)
deserialize_onetoone(mapper, key, value)
deserialize_relation(rel_mapper, value)
exclude_by(query, conditions)
Parameters:
  • query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
  • conditions (dict) – conditions dictionary
Returns:

modified query

Return type:

sqlalchemy.orm.query.Query

filter_by(query, conditions, order_criteria=None)
Parameters:
  • query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
  • conditions (dict) – conditions dictionary
  • order_criteria (dict) – optional order criteria
Returns:

modified query

Return type:

sqlalchemy.orm.query.Query

get_data(req, resp)
Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
get_default_schema(model_class, method='POST')

Returns a schema to be used in falconjsonio.schema.request_schema decorator :return:

get_eager_queryset(req, resp, db_session=None, limit=None)[source]

Return a default query with eager options set if any relations has been requested.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
  • limit (int | None) – max number of records fetched
Returns:

a query from object_class

get_object_list(queryset, limit=None, offset=None)[source]
get_or_create(db_session, model_class, query_attrs, update_attrs=None, update_existing=False)

Fetches the record and if it doesn’t exist yet, creates it, handling a race condition.

Parameters:
  • db_session (sqlalchemy.orm.session.Session) – session within DB connection
  • model_class (class) – class of the model to return or create
  • query_attrs (dict) – attributes used to fetch the model
  • update_attrs (dict) – attributes used to create a new model
  • update_existing (bool) – if True and update_attrs are set, updates existing records
Returns:

existing or new object and a flag if existing or new object is being returned

Return type:

tuple

get_param_or_post(req, name, default=None, pop_params=True)

Gets specified param from request params or body. If found in params, it’s removed.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • name (str) – param name
  • default – Default value
  • pop_params (bool) – if True, will pop from req params
Returns:

param extracted from query params or request body

get_param_totals(req)

Gets the totals and total_count params and normalizes them into a single list.

Parameters:req (falcon.request.Request) – Falcon request
Returns:total expressions
Return type:list
get_queryset(req, resp, db_session=None, limit=None)[source]

Return a query object used to fetch data.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
  • limit (int | None) – max number of records fetched
Returns:

a query from object_class

get_schema
get_special_params()[source]
get_total_objects(queryset, totals)[source]
get_tsquery(value, default_op)
next_alias(aliases, name, obj_class, use_existing=True, prefix='')
on_get(req, resp)[source]
on_head(req, resp)[source]
on_options(req, resp, **kwargs)

Returns allowed methods in the Allow HTTP header. Also returns a JSON Schema, if supported by current resource.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_post(req, resp, *args, **kwargs)[source]
on_put(req, resp, *args, **kwargs)

Add (create) a new record to the collection.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
order_by(query, criteria)
Parameters:query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
Returns:modified query
Return type:sqlalchemy.orm.query.Query
render_response(result, req, resp, status='200 OK')
Parameters:
  • result – Data to be returned in the response
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • status (str) – HTTP status code
save_resource(obj, data, db_session)

Extracts relation dicts from data, saves them and then updates the main object.

Parameters:
  • obj (object) – a new or existing model
  • data (dict) – data to assign to the model and/or its relations
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
save_resource_relations(obj, data, db_session)
serialize(obj, skip_primary_key=False, skip_foreign_keys=False, relations_level=1, relations_ignore=None, relations_include=None)

Converts the object to a serializable dictionary. :param obj: the object to serialize

Parameters:
  • skip_primary_key (bool) – should primary keys be skipped
  • skip_foreign_keys (bool) – should foreign keys be skipped
  • relations_level (int) – how many levels of relations to serialize
  • relations_ignore (list) – relationship names to ignore
  • relations_include (list) – relationship names to include
Returns:

a serializable dictionary

Return type:

dict

serialize_column(column, value)
serialize_columns(obj, data, skip_primary_key=False, skip_foreign_keys=False)
serialize_relations(obj, data, relations_level=1, relations_ignore=None, relations_include=None)
session_scope(db_engine=None, session_class=None)

Provide a scoped db session for a series of operarions. The session is created immediately before the scope begins, and is closed on scope exit. :param db_engine: SQLAlchemy Engine or other Connectable :type db_engine: sqlalchemy.engine.Connectable

Parameters:session_class (sqlalchemy.orm.Session) – SQLAlchemy Session
update_or_create(db_session, mapper, attributes)

Updated the record if attributes contain the primary key value(s) and creates it if they don’t.

Parameters:
  • db_session (sqlalchemy.orm.session.Session) –
  • mapper (sqlalchemy.orm.mapper.Mapper) –
  • attributes (dict) –
Returns:

Return type:

object

class api.resources.sqlalchemy.SingleResource(objects_class, db_engine)[source]

Allows to fetch a single resource (GET) and to update (PATCH, PUT) or remove it (DELETE). When fetching a resource (GET), following params are supported: * relations - list of relation names to include in the result, uses special value _all for all relations User input can be validated by attaching the falconjsonio.schema.request_schema() decorator.

DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
IGNORE_UNKNOWN_FILTER = False
MULTIVALUE_SEPARATOR = ','
PARAM_RELATIONS = 'relations'
PARAM_RELATIONS_ALL = '_all'
RELATIONS_AS_LIST = True
VIOLATION_FOREIGN_KEY = '23503'
clean(data)

Called after deserialize(), might perform more complex data filtering and validation.

Parameters:data (dict) –
Returns:a tuple of data and errors after additional cleanup
clean_relations(relations)

Checks all special values in relations and makes sure to always return either a list or None.

Parameters:relations (str | list) – relation names
Returns:either a list (may be empty) or None if all relations should be included
Return type:list[str] | None
delete(req, resp, obj, db_session=None)[source]

Delete an existing record. :param req: Falcon request :type req: falcon.request.Request

Parameters:
  • resp (falcon.response.Response) – Falcon response
  • obj – the object to delete
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
deserialize(data, mapper=None)

Converts incoming data to internal types. Detects relation objects. Moves one to one relation attributes to a separate key. Silently skips unknown attributes.

Parameters:
  • data (dict) – incoming data
  • mapper (sqlalchemy.orm.mapper.Mapper) – mapper, if None, mapper of the main object class will be used
Returns:

data with correct types

Return type:

dict

deserialize_column(column, value)
deserialize_onetoone(mapper, key, value)
deserialize_relation(rel_mapper, value)
exclude_by(query, conditions)
Parameters:
  • query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
  • conditions (dict) – conditions dictionary
Returns:

modified query

Return type:

sqlalchemy.orm.query.Query

filter_by(query, conditions, order_criteria=None)
Parameters:
  • query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
  • conditions (dict) – conditions dictionary
  • order_criteria (dict) – optional order criteria
Returns:

modified query

Return type:

sqlalchemy.orm.query.Query

get_default_schema(model_class, method='POST')

Returns a schema to be used in falconjsonio.schema.request_schema decorator :return:

get_object(req, resp, path_params, for_update=False, db_session=None)[source]
Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • path_params (dict) – path params extracted from URL path
  • for_update (bool) – if the object is going to be updated or deleted
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
get_or_create(db_session, model_class, query_attrs, update_attrs=None, update_existing=False)

Fetches the record and if it doesn’t exist yet, creates it, handling a race condition.

Parameters:
  • db_session (sqlalchemy.orm.session.Session) – session within DB connection
  • model_class (class) – class of the model to return or create
  • query_attrs (dict) – attributes used to fetch the model
  • update_attrs (dict) – attributes used to create a new model
  • update_existing (bool) – if True and update_attrs are set, updates existing records
Returns:

existing or new object and a flag if existing or new object is being returned

Return type:

tuple

get_param_or_post(req, name, default=None, pop_params=True)

Gets specified param from request params or body. If found in params, it’s removed.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • name (str) – param name
  • default – Default value
  • pop_params (bool) – if True, will pop from req params
Returns:

param extracted from query params or request body

get_schema
get_tsquery(value, default_op)
next_alias(aliases, name, obj_class, use_existing=True, prefix='')
on_delete(req, resp, *args, **kwargs)[source]
on_get(req, resp, *args, **kwargs)[source]
on_head(req, resp, *args, **kwargs)[source]
on_options(req, resp, **kwargs)

Returns allowed methods in the Allow HTTP header. Also returns a JSON Schema, if supported by current resource.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_patch(req, resp, *args, **kwargs)

Updates a single record. Changes only specified fields.

Parameters:
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
on_put(req, resp, *args, **kwargs)[source]
order_by(query, criteria)
Parameters:query (sqlalchemy.orm.query.Query) – SQLAlchemy Query object
Returns:modified query
Return type:sqlalchemy.orm.query.Query
render_response(result, req, resp, status='200 OK')
Parameters:
  • result – Data to be returned in the response
  • req (falcon.request.Request) – Falcon request
  • resp (falcon.response.Response) – Falcon response
  • status (str) – HTTP status code
save_resource(obj, data, db_session)

Extracts relation dicts from data, saves them and then updates the main object.

Parameters:
  • obj (object) – a new or existing model
  • data (dict) – data to assign to the model and/or its relations
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
save_resource_relations(obj, data, db_session)
serialize(obj, skip_primary_key=False, skip_foreign_keys=False, relations_level=1, relations_ignore=None, relations_include=None)

Converts the object to a serializable dictionary. :param obj: the object to serialize

Parameters:
  • skip_primary_key (bool) – should primary keys be skipped
  • skip_foreign_keys (bool) – should foreign keys be skipped
  • relations_level (int) – how many levels of relations to serialize
  • relations_ignore (list) – relationship names to ignore
  • relations_include (list) – relationship names to include
Returns:

a serializable dictionary

Return type:

dict

serialize_column(column, value)
serialize_columns(obj, data, skip_primary_key=False, skip_foreign_keys=False)
serialize_relations(obj, data, relations_level=1, relations_ignore=None, relations_include=None)
session_scope(db_engine=None, session_class=None)

Provide a scoped db session for a series of operarions. The session is created immediately before the scope begins, and is closed on scope exit. :param db_engine: SQLAlchemy Engine or other Connectable :type db_engine: sqlalchemy.engine.Connectable

Parameters:session_class (sqlalchemy.orm.Session) – SQLAlchemy Session
update(req, resp, data, obj, db_session=None)[source]

Create a new or update an existing record using provided data. :param req: Falcon request :type req: falcon.request.Request

Parameters:
  • resp (falcon.response.Response) – Falcon response
  • data (dict) –
  • obj – the object to update
  • db_session (sqlalchemy.orm.session.Session) – SQLAlchemy session
Returns:

created or updated object, serialized to a dict

Return type:

dict

update_or_create(db_session, mapper, attributes)

Updated the record if attributes contain the primary key value(s) and creates it if they don’t.

Parameters:
  • db_session (sqlalchemy.orm.session.Session) –
  • mapper (sqlalchemy.orm.mapper.Mapper) –
  • attributes (dict) –
Returns:

Return type:

object