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 plume.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

MongoSchema does not override any marshmallow methods. Instead it provides new methods which are recognised by plumes ‘Resource’ classes. Therefore, the database will not be affected if you call dump/dumps

or load/loads

Note: 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

delete(filter_spec)[source]

Delete an existing document

find(*args, **kwargs)[source]

Wraps pymongo’s find for this collection

get(filter_spec, *args, **kwargs)[source]

Wraps pymongo’s find_one for this collection

get_collection()[source]

Return the pymongo collection associated with this schema.

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 GET requests.

Parameters:req (falcon.Request) – processed
Returns:
A dictionary containing keyword arguments which
can be passed directly to pymongos’ find method. defaults to an empty dictionary (no filters applied)
Return type:dict
patch(filter_spec, data, jsonpatch=False)[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. By default, JSON data is expected to be expressed using MongoDB update operators (https://docs.mongodb.com/manual/reference/operator/update/) By passing jsonpatch=True data can be formatted according to the JSONPatch specification (http://jsonpatch.com/). This support is experimental
  • jsonpatch (boolean, False) – Enable experimental support for jsonpatch. In this case, data should follow the jsonpatch format
post(data)[source]

Creates a new document in the mongodb database.

Uses marshmallows’ loads method 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
put(filter_spec, data)[source]

‘Put’ (replace) an existing document

See documentation for MongoSchema.patch

Some useful fields for using marshmallow as a MongoDB ORM are also provided.

class plume.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 plume.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

class plume.fields.Password(password_checker=<class 'passlib.handlers.sha2_crypt.sha256_crypt'>, *args, **kwargs)[source]

Password field

class plume.fields.Slug(populate_from=None, *args, **kwargs)[source]

Represents a slug. Massages the input value to a lowercase string without spaces.

Resources and hooks

Resource classes for creating a JSON restful API.

class plume.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 _post method if appropriate.

Parameters:
  • schema (plume.schema.MongoSchema) – An instance of a MongoSchema child class on which the Collection instance should operate.
  • uri_template (str) – See plume.resource.PlumeResource
  • content_types (tuple or list) – See plume.resource.PlumeResource. Defaults to 'application/json'
  • methods (str) – See plume.resource.PlumeResource. Defaults to ('get', 'post')
  • error_handler (callable) – See plume.resource.PlumeResource.
class plume.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 plume.resource.FileItem(store, uri_template='/files/{name}', content_types=None, methods=('get', ))[source]

Item resource for interacting with single files

class plume.resource.Item(schema, uri_template, content_types='application/json', methods=('get', 'patch', 'put', 'delete'), error_handler=<function basic_error_handler>, use_jsonpatch=False)[source]

Generic class for getting/editing a single data item via a schema

Parameters:
  • schema (plume.schema.MongoSchema) – An instance of a MongoSchema child class on which the Item instance should operate.
  • uri_template (str) – See plume.resource.PlumeResource
  • content_types (tuple or list) – See plume.resource.PlumeResource. Defaults to 'application/json'
  • methods (str) – See plume.resource.PlumeResource. Defaults to ('get', 'put', 'patch', 'delete')
  • error_handler (callable) – See plume.resource.PlumeResource.
class plume.resource.PlumeResource(uri_template, content_types=('application/json', ), methods=('get', 'patch', 'put', 'delete', 'post'), error_handler=<function basic_error_handler>, use_jsonpatch=False, schema=None)[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 named on_<method> but simple _<method>.

Allowed content types are passed for the same reason. A sub class could check these using the validated_content_type hooks. This is mostly useful for file uploads (see FileCollection or FileItem) 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 plume.create_app factory function) and for setting Location headers.
  • 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 set is 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 plume.resource.basic_error_handler
uri_template

The URI template for this resource

plume.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 PlumeResource

plume.hooks.validate_content_type(req, resp, resource, params)[source]

Validate the content type of a PlumeResource

Storage

plume.storage.unique_id()[source]

Simplistic unique ID generation. The returned ID is just the current timestamp (in ms) converted to hex

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

plume.connection.connect(database='default', alias='default', **kwargs)[source]

Connect to a database or retrieve an existing connection

plume.connection.disconnect(alias='default')[source]

Close the connection with a given alias.

plume.connection.get_database(alias='default')[source]

Get an existing database