mozilla

Cornice API

Service

This document describes the methods proposed by cornice. It is automatically generated from the source code.

class cornice.service.Service(name, path, description=None, cors_policy=None, depth=1, **kw)

Contains a service definition (in the definition attribute).

A service is composed of a path and many potential methods, associated with context.

All the class attributes defined in this class or in children are considered default values.

Parameters:
  • name – The name of the service. Should be unique among all the services.
  • path – The path the service is available at. Should also be unique.
  • renderer – The renderer that should be used by this service. Default value is ‘simplejson’.
  • description – The description of what the webservice does. This is primarily intended for documentation purposes.
  • validators – A list of callables to pass the request into before passing it to the associated view.
  • filters – A list of callables to pass the response into before returning it to the client.
  • accept – A list of Accept header values accepted for this service (or method if overwritten when defining a method). It can also be a callable, in which case the values will be discovered at runtime. If a callable is passed, it should be able to take the request as a first argument.
  • content_type – A list of Content-Type header values accepted for this service (or method if overwritten when defining a method). It can also be a callable, in which case the values will be discovered at runtime. If a callable is passed, it should be able to take the request as a first argument.
  • factory – A factory returning callables which return boolean values. The callables take the request as their first argument and return boolean values. This param is exclusive with the ‘acl’ one.
  • acl – A callable defining the ACL (returns true or false, function of the given request). Exclusive with the ‘factory’ option.
  • permission – As for pyramid.config.Configurator.add_view(). Note: acl and permission can also be applied to instance method decorators such as get() and put().
  • klass – The class to use when resolving views (if they are not callables)
  • error_handler – A callable which is used to render responses following validation failures. Defaults to ‘json_error’.
  • traverse – A traversal pattern that will be passed on route declaration and that will be used as the traversal path.

There are also a number of parameters that are related to the support of CORS (Cross Origin Resource Sharing). You can read the CORS specification at http://www.w3.org/TR/cors/

Parameters:
  • cors_enabled – To use if you especially want to disable CORS support for a particular service / method.
  • cors_origins – The list of origins for CORS. You can use wildcards here if needed, e.g. (‘list’, ‘of’, ‘*.domain’).
  • cors_headers – The list of headers supported for the services.
  • cors_credentials – Should the client send credential information (False by default).
  • cors_max_age – Indicates how long the results of a preflight request can be cached in a preflight result cache.
  • cors_expose_all_headers – If set to True, all the headers will be exposed and considered valid ones (Default: True). If set to False, all the headers need be explicitly mentioned with the cors_headers parameter.
  • cors_policy

    It may be easier to have an external object containing all the policy information related to CORS, e.g:

    >>> cors_policy = {'origins': ('*',), 'max_age': 42,
    ...                'credentials': True}
    

    You can pass a dict here and all the values will be unpacked and considered rather than the parameters starting by cors_ here.

See https://pyramid.readthedocs.io/en/1.0-branch/glossary.html#term-acl for more information about ACLs.

Service cornice instances also have methods get(), post(), put(), options() and delete() are decorators that can be used to decorate views.

cornice.service.decorate_view(view, args, method)

Decorate a given view with cornice niceties.

This function returns a function with the same signature than the one you give as :param view:

Parameters:
  • view – the view to decorate
  • args – the args to use for the decoration
  • method – the HTTP method

Resource

cornice.resource.resource(depth=2, **kw)

Class decorator to declare resources.

All the methods of this class named by the name of HTTP resources will be used as such. You can also prefix them by "collection_" and they will be treated as HTTP methods for the given collection path (collection_path), if any.

Parameters:
  • depth – Witch frame should be looked in default 2.
  • kw – Keyword arguments configuring the resource.

Here is an example:

@resource(collection_path='/users', path='/users/{id}')
cornice.resource.view(**kw)

Method decorator to store view arguments when defining a resource with the @resource class decorator

Parameters:kw – Keyword arguments configuring the view.
cornice.resource.add_view(func, **kw)

Method to store view arguments when defining a resource with the add_resource class method

Parameters:
  • func – The func to hook to
  • kw – Keyword arguments configuring the view.

Example:

class User(object):

    def __init__(self, request):
        self.request = request

    def collection_get(self):
        return {'users': _USERS.keys()}

    def get(self):
        return _USERS.get(int(self.request.matchdict['id']))

add_view(User.get, renderer='json')
add_resource(User, collection_path='/users', path='/users/{id}')
cornice.resource.add_resource(klass, depth=1, **kw)

Function to declare resources of a Class.

All the methods of this class named by the name of HTTP resources will be used as such. You can also prefix them by "collection_" and they will be treated as HTTP methods for the given collection path (collection_path), if any.

Parameters:
  • klass – The class (resource) on witch to register the service.
  • depth – Witch frame should be looked in default 2.
  • kw – Keyword arguments configuring the resource.

Here is an example:

class User(object):
    pass

add_resource(User, collection_path='/users', path='/users/{id}')

Validation

cornice.validators.extract_cstruct(request)

Extract attributes from the specified request such as body, url, path, method, querystring, headers, cookies, and returns them in a single dict object.

Parameters:request (Request) – Current request
Returns:A mapping containing most request attributes.
Return type:dict
cornice.validators.colander_body_validator(request, schema=None, deserializer=None, **kwargs)

Validate the body against the schema defined on the service.

The content of the body is deserialized, validated and stored in the request.validated attribute.

Note

If no schema is defined, this validator does nothing.

Parameters:
cornice.validators.colander_validator(request, schema=None, deserializer=None, **kwargs)

Validate the full request against the schema defined on the service.

Each attribute of the request is deserialized, validated and stored in the request.validated attribute (eg. body in request.validated['body']).

Note

If no schema is defined, this validator does nothing.

Parameters:

Errors

class cornice.errors.Errors(status=400)

Holds Request errors