pyramid_jsonapi.collection_view module

Provide base class for collection views and utilities.

class pyramid_jsonapi.collection_view.CollectionViewBase(request)[source]

Bases: object

Base class for all view classes.

Parameters

request (pyramid.request) – passed by framework.

classmethod add_stage_handler(methods, stages, hfunc, add_after='end', add_existing=False)[source]

Add a stage handler to stages of view methods.

Parameters
  • methods – an iterable of view method names (get, collection_get etc.).

  • stages – an iterable of stage names.

  • hfunc – the handler function.

  • add_existing – If True, add this handler even if it exists in the deque.

  • add_after – ‘start’, ‘end’, or an existing function.

all_attributes = None
property allowed_fields

Set of fields to which current action is allowed.

Returns

set of allowed field names.

Return type

set

allowed_object(obj)[source]

Whether or not current action is allowed on object.

Returns

Return type

bool

property allowed_requested_query_columns

All columns required in query to fetch allowed requested fields from db.

Returns

Union of allowed requested_attributes and allowed_requested_relationships_local_columns

Return type

dict

property allowed_requested_relationships_local_columns

Finds all the local columns for allowed MANYTOONE relationships.

Returns

local columns indexed by column name.

Return type

dict

api = None
association_proxy_query(obj_id, rel, full_object=True)[source]

Construct query for related objects across an association proxy.

Parameters
  • obj_id (str) – id of an item in this view’s collection.

  • proxy (sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance) – the relationships to get related objects from.

  • full_object (bool) – if full_object is True, query for all requested columns (probably to build resource objects). If full_object is False, only query for the key column (probably to build resource identifiers).

Returns

query which will fetch related object(s).

Return type

sqlalchemy.orm.query.Query

attributes = None
property bad_include_paths

Return a set of invalid ‘include’ parameters.

Query Parameters

include: comma separated list of related resources to include in the include section.

Returns

set of requested include paths with no corresponding attribute.

Return type

set

base_collection_query(loadonly=None)[source]
callbacks = None
collection_get_old()[source]

Handle GET requests for the collection.

Get a set of items from the collection, possibly matching search/filter parameters. Optionally sort the results, page them, return only certain fields, and include related resources.

Query Parameters

include: comma separated list of related resources to include in the include section.

fields[<collection>]: comma separated list of fields (attributes or relationships) to include in data.

sort: comma separated list of sort keys.

page[limit]: number of results to return per page.

page[offset]: starting index for current page.

filter[<attribute>:<op>]: filter operation.

Returns

in the form:

{
    "data": [ list of resource objects ],
    "links": { links object },
    "include": [ optional list of included resource objects ],
    "meta": { implementation specific information }
}

Return type

jsonapi.Document

Raises

HTTPBadRequest

Examples

Get up to default page limit people resources:

http GET http://localhost:6543/people

Get the second page of two people, reverse sorted by name and include the related posts as included documents:

http GET http://localhost:6543/people?page[limit]=2&page[offset]=2&sort=-name&include=posts
collection_name = None
collection_post_old()[source]

Handle POST requests for the collection.

Create a new object in collection.

Request Body

resource object (json) in the form:

{
    "data": { resource object }
}
Returns

in the form:

{
    "data": { resource object },
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

Return type

jsonapi.Document

Raises
  • HTTPForbidden – if an id is presented in “data” and client ids are

  • not supported.

  • HTTPConflict – if type is not present or is different from the

  • collection name.

  • HTTPNotFound – if a non existent relationship is referenced in the

  • supplied resource object.

  • HTTPConflict – if creating the object would break a database

  • constraint (most commonly if an id is supplied by the client and

  • an item with that id already exists)

  • HTTPBadRequest – if the request is malformed in some other way.

Examples

Create a new person with name ‘monty’ and let the server pick the id:

http POST http://localhost:6543/people data:='
{
    "type":"people",
    "attributes": {
        "name": "monty"
    }
}' Content-Type:application/vnd.api+json
classmethod collection_query_info(request)[source]

Return dictionary of information used during DB query.

Parameters

request (pyramid.request) – request object.

Returns

query info in the form:

{
    'page[limit]': maximum items per page,
    'page[offset]': offset for current page (in items),
    'sort': sort param from request,
    '_sort': [
        {
            'key': sort key ('field' or 'relationship.field'),
            'ascending': sort ascending or descending (bool)
        },
        ...
    },
    '_filters': {
        filter_param_name: {
            'colspec': list of columns split on '.',
            'op': filter operator,
            'value': value of filter param,
        }
    },
    '_page': {
        paging_param_name: value,
        ...
    }
}

Keys beginning with ‘_’ are derived.

Return type

dict

dbsession = None
default_limit = None
delete_old()[source]

Handle DELETE request for single item.

Delete the referenced item from the collection.

URL (matchdict) Parameters

id (str): resource id

Returns

Resource Identifier for deleted object.

Return type

jsonapi.Document

Raises
  • HTTPFailedDependency – if a database constraint would be broken by

  • deleting the specified resource from the relationship.

Example

delete person 1:

http DELETE http://localhost:6543/people/1
exposed_fields = None
fields = None
get_item(_id=None)[source]

Return the item specified by _id. Will look up id from request if _id is None.

get_old()[source]

Handle GET request for a single item.

Get a single item from the collection, referenced by id.

URL (matchdict) Parameters

id (str): resource id

Returns

in the form:

{
    "data": { resource object },
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

Return type

jsonapi.Document

Raises

HTTPNotFound

Example

Get person 1:

http GET http://localhost:6543/people/1
get_one(query, not_found_message=None)[source]
hybrid_attributes = None
static id_col(item)[source]

Return the column holding an item’s id.

item = None
key_column = None
mapped_info_from_name(name, model=None)[source]

Get the pyramid_jsonapi info dictionary for a mapped object.

Parameters
  • name (str) – name of object.

  • model (sqlalchemy.ext.declarative.declarative_base) – model to inspect. Defaults to self.model.

max_limit = None
methods = None
model()
model_from_table(table)[source]

Find the model class mapped to a table.

not_found_message = None
obj_id = None
object_exists(obj_id)[source]

Test if object with id obj_id exists.

Parameters

obj_id (str) – object id

Returns

True if object exists, False if not.

Return type

bool

Return a dictionary of pagination links.

Parameters

count (int) – total number of results available.

Returns

dictionary of named links.

Return type

dict

patch_old()[source]

Handle PATCH request for a single item.

Update an existing item from a partially defined representation.

URL (matchdict) Parameters

id (str): resource id

Request Body

Partial resource object (json)

Returns

in the form:

{
    'meta': {
        'updated': [
            <attribute_name>,
            <attribute_name>
        ]
    }
}

Return type

jsonapi.Document

Raises

HTTPNotFound

Example

PATCH person 1, changing name to alicia:

http PATCH http://localhost:6543/people/1 data:='
{
    "type":"people", "id": "1",
    "attributes": {
        "name": "alicia"
    }
}' Content-Type:application/vnd.api+json

Change the author of posts/1 to people/2:

http PATCH http://localhost:6543/posts/1 data:='
{
    "type":"posts", "id": "1",
    "relationships": {
        "author": {"type": "people", "id": "2"}
    }
}' Content-Type:application/vnd.api+json

Set the comments on posts/1 to be [comments/4, comments/5]:

http PATCH http://localhost:6543/posts/1 data:='
{
    "type":"posts", "id": "1",
    "relationships": {
        "comments": [
            {"type": "comments", "id": "4"},
            {"type": "comments", "id": "5"}
        ]
    }
}' Content-Type:application/vnd.api+json
path_is_included(path)[source]

Test if path is in requested includes.

Parameters

path (list) – list representation if include path to test.

Returns

True if path is in requested includes.

Return type

bool

permission_filter(permission, target_type, stage_name, default=None)[source]

Find the permission filter given a permission and stage name.

permission_filters = None
classmethod permission_handler(endpoint_name, stage_name)[source]
permission_object(attributes=None, relationships=None, id=None, subtract_attributes=frozenset({}), subtract_relationships=frozenset({}))[source]
permission_template = None
query_add_filtering(query)[source]

Add filtering clauses to query.

Use information from the filter query parameter (via collection_query_info()) to filter query results.

Filter parameter structure:

filter[<attribute>:<op>]=<value>

where:

attribute is an attribute of the queried object type.

op is the comparison operator.

value is the value the comparison operator should compare to.

Valid comparison operators:

Only operators added via self.api.filter_registry.register() are considered valid. Get a list of filter names with self.api.filter_registry.valid_filter_names()

See also

_filters key from collection_query_info()

Query Parameters

filter[<attribute>:<op>]: filter operation.

Parameters

query (sqlalchemy.orm.query.Query) – query

Returns

filtered query.

Return type

sqlalchemy.orm.query.Query

Examples

Get people whose name is ‘alice’

http GET http://localhost:6543/people?filter[name:eq]=alice

Get posts published after 2015-01-03:

http GET http://localhost:6543/posts?filter[published_at:gt]=2015-01-03
query_add_sorting(query)[source]

Add sorting to query.

Use information from the sort query parameter (via collection_query_info()) to contruct an order_by clause on the query.

See also

_sort key from collection_query_info()

Query Parameters

sort: comma separated list of sort keys.

Parameters

query (sqlalchemy.orm.query.Query) – query

Returns

query with order_by clause.

Return type

sqlalchemy.orm.query.Query

classmethod register_permission_filter(permissions, stages, pfunc, target_types=[<Targets.collection: 1>, <Targets.item: 2>, <Targets.relationship: 3>])[source]
rel = None
rel_class = None
rel_view = None
related_get_old()[source]

Handle GET requests for related URLs.

Get object(s) related to a specified object.

URL (matchdict) Parameters

id (str): resource id relname (str): relationship name

Query Parameters

sort: comma separated list of sort keys.

filter[<attribute>:<op>]: filter operation.

Returns

in the form:

For a TOONE relationship (return one object):

{
    "data": { resource object },
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

For a TOMANY relationship (return multiple objects):

{
    "data": [ { resource object }, ... ]
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

Return type

jsonapi.Document

Raises
  • HTTPNotFound – if relname is not found as a relationship.

  • HTTPBadRequest – if a bad filter is used.

Examples

Get the author of post 1:

http GET http://localhost:6543/posts/1/author
related_limit(relationship)[source]

Paging limit for related resources.

Query Parameters

page[limit:relationships:<relname>]: number of results to return per page for related resource <relname>.

Parameters

relationship (sqlalchemy.orm.relationships.RelationshipProperty) – the relationship to get the limit for.

Returns

paging limit for related resources.

Return type

int

related_query(obj, relationship, full_object=True)[source]

Construct query for related objects.

Parameters
  • obj_id (str) – id of an item in this view’s collection.

  • relationship – the relationship object to get related objects from. This can be a RelationshipProperty or AssociationProxy object.

  • related_to (model class or None) – the class the relationship is coming from. AssociationProxy relationships use this. It defaults to None, which is interpreted as self.model.

  • full_object (bool) – if full_object is True, query for all requested columns (probably to build resource objects). If full_object is False, only query for the key column (probably to build resource identifiers).

Returns

query which will fetch related object(s).

Return type

sqlalchemy.orm.query.Query

relationships = None
relationships_delete_old()[source]

Handle DELETE requests for TOMANY relationships.

Delete the specified member from the relationship.

URL (matchdict) Parameters

id (str): resource id relname (str): relationship name

Request Body

resource identifier list (json) in the form:

{
    "data": [ { resource identifier },... ]
}
Returns

in the form:

{
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

Return type

jsonapi.Document

Raises
  • HTTPNotFound – if there is no <relname> relationship.

  • HTTPNotFound – if an attempt is made to modify a TOONE relationship.

  • HTTPConflict – if a resource identifier is specified with a

  • different type than that which the collection holds.

  • HTTPFailedDependency – if a database constraint would be broken by

  • adding the specified resource to the relationship.

Examples

Delete comments/1 from posts/1 comments:

http DELETE http://localhost:6543/posts/1/relationships/comments data:='
[
    { "type": "comments", "id": "1" }
]' Content-Type:application/vnd.api+json
relationships_get_old()[source]

Handle GET requests for relationships URLs.

Get object identifiers for items referred to by a relationship.

URL (matchdict) Parameters

id (str): resource id relname (str): relationship name

Query Parameters

sort: comma separated list of sort keys.

filter[<attribute>:<op>]: filter operation.

Returns

in the form:

For a TOONE relationship (return one identifier):

{
    "data": { resource identifier },
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

For a TOMANY relationship (return multiple identifiers):

{
    "data": [ { resource identifier }, ... ]
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

Return type

jsonapi.Document

Raises

HTTPBadRequest – if a bad filter is used.

Examples

Get an identifer for the author of post 1:

http GET http://localhost:6543/posts/1/relationships/author
relationships_patch_old()[source]

Handle PATCH requests for relationships (TOMANY or TOONE).

Completely replace the relationship membership.

URL (matchdict) Parameters

id (str): resource id relname (str): relationship name

Request Body

resource identifier list (json) in the form:

TOONE relationship:

{
    "data": { resource identifier }
}

TOMANY relationship:

{
    "data": [ { resource identifier },... ]
}
Returns

in the form:

{
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

Return type

jsonapi.Document

Raises
  • HTTPNotFound – if there is no <relname> relationship.

  • HTTPConflict – if a resource identifier is specified with a

  • different type than that which the collection holds.

  • HTTPFailedDependency – if a database constraint would be broken by

  • adding the specified resource to the relationship.

Examples

Replace comments list of posts/1:

http PATCH http://localhost:6543/posts/1/relationships/comments data:='
[
    { "type": "comments", "id": "1" },
    { "type": "comments", "id": "2" }
]' Content-Type:application/vnd.api+json
relationships_post_old()[source]

Handle POST requests for TOMANY relationships.

Add the specified member to the relationship.

URL (matchdict) Parameters

id (str): resource id relname (str): relationship name

Request Body

resource identifier list (json) in the form:

{
    "data": [ { resource identifier },... ]
}
Returns

in the form:

{
    "links": {
        "self": self url,
        maybe other links...
    },
    "meta": { jsonapi specific information }
}

Return type

jsonapi.Document

Raises
  • HTTPNotFound – if there is no <relname> relationship.

  • HTTPNotFound – if an attempt is made to modify a TOONE relationship.

  • HTTPConflict – if a resource identifier is specified with a

  • different type than that which the collection holds.

  • HTTPFailedDependency – if a database constraint would be broken by

  • adding the specified resource to the relationship.

Examples

Add comments/1 as a comment of posts/1

http POST http://localhost:6543/posts/1/relationships/comments data:='
[
    { "type": "comments", "id": "1" }
]' Content-Type:application/vnd.api+json
relname = None
request = None
property requested_attributes

Return a dictionary of attributes.

Query Parameters

fields[<collection>]: comma separated list of fields (attributes or relationships) to include in data.

Returns

dict in the form:

{
    <colname>: <column_object>,
    ...
}

Return type

dict

property requested_field_names

Get the sparse field names from request.

Query Parameters

fields[<collection>]: comma separated list of fields (attributes or relationships) to include in data.

Returns

set of field names.

Return type

set

property requested_fields

Union of attributes and relationships.

Query Parameters

fields[<collection>]: comma separated list of fields (attributes or relationships) to include in data.

Returns

dict in the form:

{
    <colname>: <column_object>,
    ...
    <relname>: <relationship_object>,
    ...
}

Return type

dict

requested_include_names()[source]

Parse any ‘include’ param in http request.

Returns

names of all requested includes.

Return type

set

Default:

set: names of all direct relationships of self.model.

property requested_relationships

Return a dictionary of relationships.

Query Parameters

fields[<collection>]: comma separated list of fields (attributes or relationships) to include in data.

Returns

dict in the form:

{
    <relname>: <relationship_object>,
    ...
}

Return type

dict

settings = None
single_item_query(obj_id=None, loadonly=None)[source]

A query representing the single item referenced by id.

Keyword Arguments
  • obj_id – id of object to be fetched. If None then use the id from the URL.

  • loadonly – which attributes to load. If None then all requested attributes from the URL.

Returns

query which will fetch item with id ‘id’.

Return type

sqlalchemy.orm.query.Query

standard_relationship_query(obj_id, relationship, full_object=True)[source]

Construct query for related objects via a normal relationship.

Parameters
  • obj_id (str) – id of an item in this view’s collection.

  • relationship (sqlalchemy.orm.relationships.RelationshipProperty) – the relationships to get related objects from.

  • full_object (bool) – if full_object is True, query for all requested columns (probably to build resource objects). If full_object is False, only query for the key column (probably to build resource identifiers).

Returns

query which will fetch related object(s).

Return type

sqlalchemy.orm.query.Query

static true_filter(*args, **kwargs)[source]
view_classes = None
view_instance(model)[source]

(memoised) get an instance of view class for model.

Parameters

model (DeclarativeMeta) – model class.

Returns

subclass of CollectionViewBase providing view for model.

Return type

class

classmethod wrap_permission_filter(permission, stage, pfunc)[source]
class pyramid_jsonapi.collection_view.Entity(type)

Bases: tuple

type

Alias for field number 0

class pyramid_jsonapi.collection_view.RQLQuery(entities, session=None)[source]

Bases: sqlalchemy.orm.query.Query, rqlalchemy.query.RQLQueryMixIn