API Reference¶
Schemas and fields¶
Inherit from MongoSchema to start creating schemas which are materialized to MongoDB.
A MongoSchema is just a marshmallow schema with extra functions to give it ORM-like abilities.
Connect to MongoDB and provide a base schema which will save deserialized data to a collection
The connections to mongodb are cached. Inspired by MongoEngine
-
class
feather.schema.MongoSchema(*args, **kwargs)[source]¶ A Marshmallow schema backed by MongoDB
When data is loaded (deserialized) it is saved to a mongodb document in a collection matching the Schema name (and containing app - similar to Django table names)
This enables marshmallow to behave as an ORM to MongoDB
MongoSchemadoes not override any marshmallow methods. Instead it provides new methods which are recognised by feathers ‘Resource’ classes. Therefore, the database will not be affected if you calldump/dumpsorload/loadsNote: Currently we attempt to create the database constraints when the schema is initialized. Therefore, you must connect to a database first.
-
OPTIONS_CLASS¶ alias of
MonogSchemaOpts
-
count()[source]¶ Wraps pymongo’s count for this collection.
Returns the count of all documents in the collection
-
get_filter(req)[source]¶ Create a MongoDB filter query for this schema based on an incoming request. It is intended that this method be overridden in child classes to provide per-request filtering on
GETrequests.Parameters: req (falcon.Request) – processed Returns: - A dictionary containing keyword arguments which
- can be passed directly to pymongos’
findmethod. defaults to an empty dictionary (no filters applied)
Return type: dict
-
patch(filter_spec, data)[source]¶ ‘Patch’ (update) an existing document
Parameters: - filter_spec (dict) – The pymongo filter spec to match a single document to be updated
- data – JSON data to be validated, deserialized and used to update a document
-
post(data)[source]¶ Creates a new document in the mongodb database.
Uses marshmallows’
loadsmethod to validate and complete incoming data, before saving it to the database.Parameters: data (str) – JSON data to be validated against the schema Returns: - Tuple of (data, errors) containing the validated
- & deserialized data dict and any errors.
Return type: validated
-
Some useful fields for using marshmallow as a MongoDB ORM are also provided.
-
class
feather.fields.Choice(choices=None, *args, **kwargs)[source]¶ The input value is validated against a set of choices passed in the field definition. Upon serialization, the full choice list along with the chosen value is returned (in a dict). Only the chosen value should be passed in deserialization.
-
class
feather.fields.MongoId(default=<marshmallow.missing>, attribute=None, load_from=None, dump_to=None, error=None, validate=None, required=False, allow_none=None, load_only=False, dump_only=False, missing=<marshmallow.missing>, error_messages=None, **metadata)[source]¶ Represents a MongoDB object id
Serializes the ObjectID to a string and deserializes to an ObjectID
Resources and hooks¶
Resource classes for creating a JSON restful API.
-
class
feather.resource.Collection(schema, uri_template, content_types='application/json', methods=('get', 'post'), error_handler=<function basic_error_handler>)[source]¶ Generic class for listing/creating data via a schema
Remembering that the @ operator is just syntactic sugar, if we want to apply a decorator we could do it with minimal effort like this:
resource = Collection(…) resource.on_post = falcon.before(my_function)(resource.on_post)Alternatively, we could create a subclass:
- class MyResource(Collection):
- on_post = falcon.before(my_function)(Collection.on_post.__func__)
Also note that when overriding, you will need to manually add back the content type validation for the
_postmethod if appropriate.Parameters: - schema (feather.schema.MongoSchema) – An instance of a
MongoSchemachild class on which theCollectioninstance should operate. - uri_template (str) – See
feather.resource.FeatherResource - content_types (tuple or list) – See
feather.resource.FeatherResource. Defaults to'application/json' - methods (str) – See
feather.resource.FeatherResource. Defaults to('get', 'post') - error_handler (callable) – See
feather.resource.FeatherResource.
-
class
feather.resource.FeatherResource(uri_template, content_types={'application/json'}, methods=('get', 'patch', 'put', 'delete', 'post'), error_handler=<function basic_error_handler>)[source]¶ Base class used for setting a uri_template, allowed content types and HTTP methods provided.
By encapsulating the URI, we can provide factory methods for routing, allowing us to specify the resource and its’ uri in one place
HTTP handler methods (
on_<method>in falcon) are dynamically assigned in order to allow Resource instances to be created for with different sets of requiremets. (E.g. create a read-only collection by only passing('get',)when instantiating). This explains why the method handlers below are not namedon_<method>but simple_<method>.Allowed content types are passed for the same reason. A sub class could check these using the
validated_content_typehooks. This is mostly useful for file uploads (seeFileCollectionorFileItem) where you might wish to restrict content types (e.g. images only)Parameters: - uri_template (str) – A URI template for this resource which will be used
when routing (using the
feather.create_appfactory function) and for settingLocationheaders. - content_types (tuple, set or list) – List of allowed content_types. This is not
used by default. Instead, decorate desired handler methods with
@falcon.before(validate_content_type).
A
setis reccomended as the validation performs an exclusion (not in) operation - methods (tuple or list) – List of HTTP methods to allow.
- error_handler (callable) – A function which is responsible for handling validation
errors returned by a marshmallow schema.
Defaults to
feather.resource.basic_error_handler
-
uri_template¶ The URI template for this resource
- uri_template (str) – A URI template for this resource which will be used
when routing (using the
-
class
feather.resource.FileCollection(store, uri_template='/files', content_types=None, methods=('get', 'post'))[source]¶ Collection for posting/listing file uploads.
By default, all content types are allowed - usually you would want to limit this, e.g. just allow images by passing
('image/png', 'image/jpeg')
-
class
feather.resource.FileItem(store, uri_template='/files/{name}', content_types=None, methods=('get', ))[source]¶ Item resource for interacting with single files
-
class
feather.resource.Item(schema, uri_template, content_types='application/json', methods=('get', 'patch', 'put', 'delete'))[source]¶ Generic class for getting/editing a single data item via a schema
Parameters: - schema (feather.schema.MongoSchema) – An instance of a
MongoSchemachild class on which theIteminstance should operate. - uri_template (str) – See
feather.resource.FeatherResource - content_types (tuple or list) – See
feather.resource.FeatherResource. Defaults to'application/json' - methods (str) – See
feather.resource.FeatherResource. Defaults to('get', 'put', 'patch', 'delete') - error_handler (callable) – See
feather.resource.FeatherResource.
- schema (feather.schema.MongoSchema) – An instance of a
-
feather.resource.basic_error_handler(error_dict)[source]¶ Handle an error dictionary returned by a marshmallow schema.
This basic handler either returns a 409 conflict error if the error dictionary indicates a duplicate key, or a 400 bad request error with the error dictionary attached.
Hooks for working with a FeatherResource
Storage¶
Connecting to a database¶
Connect to MongoDB and provide a base schema which will save deserialized data to a collection
The connections to mongodb are cached. Inspired by MongoEngine