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
- allowed_object(obj)[source]¶
Whether or not current action is allowed on object.
- Returns
- Return type
- 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
- property allowed_requested_relationships_local_columns¶
Finds all the local columns for allowed MANYTOONE relationships.
- Returns
local columns indexed by column name.
- Return type
- 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
- 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
- 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
- hybrid_attributes = None¶
- 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()¶
- not_found_message = None¶
- obj_id = None¶
- 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
- permission_filter(permission, target_type, stage_name, default=None)[source]¶
Find the permission filter given a permission and stage name.
- permission_filters = None¶
- 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 (viacollection_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 fromcollection_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 (viacollection_query_info()
) to contruct anorder_by
clause on the query.See also
_sort
key fromcollection_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¶
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
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
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
- 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
- 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
- requested_include_names()[source]¶
Parse any ‘include’ param in http request.
- Returns
names of all requested includes.
- Return type
- 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
- 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
- view_classes = None¶