views

class pyramid_restful.views.APIView(**kwargs)

Base for class based views. Requests are routed to a view’s method with the same name as the HTTP method of the request.

permission_classes = []

An iterable of permissions classes. Defaults to default_permission_classes from the pyramid_restful configuration. Override this attribute to provide view specific permissions.

initial(request, *args, **kwargs)

Runs anything that needs to occur prior to calling the method handler.

get_permissions()

Instantiates and returns the list of permissions that this view requires.

check_permissions(request)

Check if the request should be permitted. Raises an appropriate exception if the request is not permitted.

Parameters:request – Pyramid Request object.
check_object_permissions(request, obj)

Check if the request should be permitted for a given object. Raises an appropriate exception if the request is not permitted.

Parameters:
  • request – Pyramid Request object.
  • obj – The SQLAlchemy model instance that permissions will be evaluated against.
options(request, *args, **kwargs)

Handles responding to requests for the OPTIONS HTTP verb.

generics

class pyramid_restful.generics.GenericAPIView(**kwargs)

Provide default functionality for working with RESTFul endpoints. pagination_class can be overridden as a class attribute:

Usage:

class MyView(GenericAPIView):
    pagination_class = MyPager
pagination_class

alias of pyramid_restful.pagination.pagenumber.PageNumberPagination

model = None

The SQLAlchemy model class used by the view.

schema_class = None

The marshmallow schema class used by the view.

filter_classes = ()

Iterable of Filter classes to be used with the view.

lookup_field = 'id'

The name of the primary key field in the model used by the view.

get_query()

Get the list of items for this view. You may want to override this if you need to provide different query depending on the incoming request. (Eg. return a list of items that is specific to the user)

Returns:sqlalchemy.orm.query.Query
get_object()

Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf.

Returns:An instance of the view’s model.
get_schema_class()

Return the class to use for the schema. Defaults to using self.schema_class. You may want to override this if you need to provide different serializations depending on the incoming request.

get_schema_context()

Extra context provided to the schema class.

get_schema(*args, **kwargs)

Return the schema instance that should be used for validating and deserializing input, and for serializing output.

filter_query(query)

Filter the given query using the filter classes specified on the view if any are specified.

paginator

The paginator instance associated with the view, or None.

paginate_query(query)

Return single page of results or None if pagination is disabled.

get_paginated_response(data)

Return a paginated style Response object for the given output data.

class pyramid_restful.generics.CreateAPIView(**kwargs)

Concrete view for creating a model instance.

class pyramid_restful.generics.ListAPIView(**kwargs)

Concrete view for listing a queryset.

class pyramid_restful.generics.RetrieveAPIView(**kwargs)

Concrete view for retrieving a model instance.

class pyramid_restful.generics.DestroyAPIView(**kwargs)

Concrete view for deleting a model instance.

class pyramid_restful.generics.UpdateAPIView(**kwargs)

Concrete view for updating a model instance.

class pyramid_restful.generics.ListCreateAPIView(**kwargs)

Concrete view for listing a queryset or creating a model instance.

class pyramid_restful.generics.RetrieveUpdateAPIView(**kwargs)

Concrete view for retrieving, updating a model instance.

class pyramid_restful.generics.RetrieveDestroyAPIView(**kwargs)

Concrete view for retrieving or deleting a model instance.

class pyramid_restful.generics.RetrieveUpdateDestroyAPIView(**kwargs)

Concrete view for retrieving, updating or deleting a model instance.

viewsets

class pyramid_restful.viewsets.ViewSetMixin

Overrides .as_view() so that it takes an actions_map keyword that performs the binding of HTTP methods to actions on the view.

For example, to create a concrete view binding the ‘GET’ and ‘POST’ methods to the ‘list’ and ‘create’ actions…

view = MyViewSet.as_view({‘get’: ‘list’, ‘post’: ‘create’})

classmethod as_view(action_map=None, **initkwargs)

Allows custom request to method routing based on given action_map kwarg.

class pyramid_restful.viewsets.APIViewSet(**kwargs)

Does not provide any actions by default.

class pyramid_restful.viewsets.GenericAPIViewSet(**kwargs)

The GenericAPIView class does not provide any actions by default, but does include the base set of generic view behavior, such as the get_object and get_query methods.

class pyramid_restful.viewsets.ReadOnlyModelViewSet(**kwargs)

A ViewSet that provides default list() and retrieve() actions.

class pyramid_restful.viewsets.ModelCRUDViewSet(**kwargs)

A ViewSet that provides default create(), retrieve(), update(), destroy() and list() actions.

class pyramid_restful.viewsets.ModelCRPDViewSet(**kwargs)

A ViewSet that provides default create(), retrieve(), partial_update(), destroy() and list() actions.

class pyramid_restful.viewsets.ModelCRUPDViewSet(**kwargs)

A viewset that provides default create(), retrieve(), partial_update(), 'update(), destroy() and list() actions.

mixins

class pyramid_restful.mixins.ListModelMixin

List objects.

class pyramid_restful.mixins.RetrieveModelMixin

Retrieve a single object.

class pyramid_restful.mixins.CreateModelMixin

Create object from serialized data.

perform_create(data)

Hook for controlling the creation of an model instance. Override this if you need to do more with your data before saving your object than just mapping the deserialized data to a new instance of self.model.

class pyramid_restful.mixins.UpdateModelMixin

Update a model instance (PUT).

perform_update(data, instance)

Hook for controlling the update of an model instance. Override this if you need to do more with your data before updating the object than just mapping the deserialized data to the attribute of the instance.

class pyramid_restful.mixins.PartialUpdateMixin

Support for partially updating instance (PATCH).

perform_partial_update(data, instance)

Hook for controlling the update of an model instance. Override this if you need to do more with your data before updating the object than just mapping the deserialized data to the attribute of the instance.

class pyramid_restful.mixins.DestroyModelMixin

Destroy a model instance.

perform_destroy(instance)

Hook for controlling the deletion of an model instance. Override this if you need to do more than just delete the instance.

class pyramid_restful.mixins.ActionSchemaMixin

Allows you to use different schema depending on the action being taken by the request. Defaults to the standard schema_class if no actions are specified.

decorators

pyramid_restful.decorators.detail_route(methods=None, **kwargs)

Used to mark a method on a ViewSet that should be routed for detail requests.

Usage:

class UserViewSet(ModelCRUDViewSet):
    model = User
    schema = UserSchema

    @detail_route(methods=['post'], url_path='lock-user')
    def lock_user(request, id):
        ...
Parameters:
  • methods – An iterable of strings representing the HTTP (GET, POST, etc.) methods accepted by the route.
  • url_path – Replaces the route automatically generated by the ViewSetRouter for the decorated method with the value provided.
pyramid_restful.decorators.list_route(methods=None, **kwargs)

Used to mark a method on a ViewSet that should be routed for list requests.

Usage:

class UserViewSet(ModelCRUDViewSet):
    model = User
    schema = UserSchema

    @list_route(methods=['get'], url_path='active-users')
    def active_users(request, *args, **kwargs):
        ...
Parameters:
  • methods – An iterable of strings representing the HTTP (GET, POST, etc.) methods accepted by the route.
  • url_path – Replaces the route automatically generated by the ViewSetRouter for the decorated method with the value provided.

routers

class pyramid_restful.routers.ViewSetRouter(configurator, trailing_slash=True)

Automatically adds routes and associates views to the Pyramid Configurator for ViewSets, including any decorated list_routes and detail_routes.

register(prefix, viewset, basename, factory=None, permission=None)

Factory and permission are likely only going to exist until I have enough time to write a permissions module for PRF.

Parameters:
  • prefix – the uri route prefix.
  • viewset – The ViewSet class to route.
  • basename – Used to name the route in pyramid.
  • factory – Optional, root factory to be used as the context to the route.
  • permission – Optional, permission to assign the route.

permissions

class pyramid_restful.permissions.BasePermission

All permission classes should inherit from this class.

message = None

Override message to customize the message associated with the exception.

has_permission(request, view)

Checked on every request to a view. Return True if permission is granted else False.

Parameters:
  • request – The request sent to the view.
  • view – The instance of the view being accessed.
Returns:

Boolean

has_object_permission(request, view, obj)

Checked when a request is for a specific object. Return True if permission is granted else False.

Parameters:
  • request – The request sent to the view.
  • view – The instance of the view being accessed.
  • obj – The object being accessed.
Returns:

Boolean

filters

class pyramid_restful.filters.BaseFilter

Base interface that that all filter classes must implement.

filter_query(request, query, view)

This method must be overridden.

Parameters:
  • request – The request being processed.
  • query – The query to be filtered.
  • view – The view the filter is being applied to.
Returns:

The filtered query.

class pyramid_restful.filters.AttributeBaseFilter

A base class for implementing filters on SQLAlchemy model attributes. Supports filtering a comma separated list using OR statements and relationship filter using the . path to attribute. WARNING: Every relationship in a . path is joined.

Expects the query string parameters to be formatted as: key[field_name]=val.

Example: filter[email]=test@exmaple.com

query_string_lookup = None

The key to use when parsing the request’s query string. The key in key[field_name]=val.

view_attribute_name = None

The name of the class attribute used in the view class that uses the filter that specifies which fields can be filtered on.

parse_query_string(params)

Override this method if you need to support query string filter keys other than those in the format of key[field_name]=val. Maps query string values == ‘null’ to None.

Parameters:params – The query string parameters from request.params.
Returns:Dictionary.
filter_query(request, query, view)

You may want to override this method if you want to add custom filtering to an ViewSet while still utilizing the feature of the AttributeFilter implementation.

Parameters:
  • request – The pyramid Request instance.
  • query – The SQLAlchemy Query instance.
  • view – An instance of the view class that the filter has been applied to.
Returns:

The filtered query.

apply_filter(query, filter_list)

Override this if you need to do something beside calling filter on the query.

Parameters:
  • query – the query that will be returned from the filter_query method.
  • filter_list – An array of SQLAlchemy comparative statements.
Returns:

The query.

build_comparision(field, value)

Must be overridden. Given the model field and the value to be filtered, this should return the statement to be appended as a filter to the final query.

class pyramid_restful.filters.FieldFilter

Filters a query based on the filter_fields set on the view. filter_fields should be a list of SQLAlchemy Model columns.

Comma separated values are treated as ORs. Multiple filter[<field>] query params are AND’d together.

Usage:

class UserViewSet(ModelCRUDViewSet):
    model = User
    schema = UserSchema
    filter_classes = (FieldFilter,)
    filter_fields = (User.email, User.name,)
build_comparision(field, value)

Must be overridden. Given the model field and the value to be filtered, this should return the statement to be appended as a filter to the final query.

class pyramid_restful.filters.SearchFilter

Implements LIKE filtering based on the search[field_name]=val querystring. Comma separated values are treated as ORs. Multiple search[<fields>] are OR’d together.

Usage:

class UserViewSet(ModelCRUDViewSet):
    model = User
    schema = UserSchema
    filter_classes = (SearchFilter,)
    filter_fields = (User.email, User.name,)
build_comparision(field, value)

Must be overridden. Given the model field and the value to be filtered, this should return the statement to be appended as a filter to the final query.

apply_filter(query, filter_list)

Override this if you need to do something beside calling filter on the query.

Parameters:
  • query – the query that will be returned from the filter_query method.
  • filter_list – An array of SQLAlchemy comparative statements.
Returns:

The query.

class pyramid_restful.filters.OrderFilter

Allow ordering of the query based on an order[field]=(asc || desc) query string.

Usage:

class UserViewSet(ModelCRUDViewSet):
    model = User
    schema = UserSchema
    filter_classes = (OrderFilter,)
    filter_fields = (User.created, User.name,)
build_comparision(field, value)

Must be overridden. Given the model field and the value to be filtered, this should return the statement to be appended as a filter to the final query.

apply_filter(query, filter_list)

Override this if you need to do something beside calling filter on the query.

Parameters:
  • query – the query that will be returned from the filter_query method.
  • filter_list – An array of SQLAlchemy comparative statements.
Returns:

The query.

expandables

class pyramid_restful.expandables.ExpandableSchemaMixin

A mixin class for marshmallow.Schema classes. Supports optionally expandable fields based on the value of the query string parameters. The query string parameter’s key is determined by the value of the QUERY_KEY class attribute.

Fields that can be expanded are defined in the schema’s Meta class using the expandable_fields attribute. The value of expandable_fields should be a dictionary who’s keys are used to match the value of the requests’s query string parameter and the value should be a marshmallow.fields.Nested definition.

Usage:

from marshmallow import Schema, fields

from pyramid_restful.expandables import ExpandableSchemaMixin

class UserSchema(ExpandableSchemaMixin, schema)
    id = fields.Integer()
    name = fields.String()
    email = fields.String()

    class Meta:
        expandable_fields = {
        'account': fields.Nested('AccountSchema')
    }
OPTIONS_CLASS

alias of ExpandableOpts

QUERY_KEY = 'expand'

The query string parameter name used for expansion.

class pyramid_restful.expandables.ExpandableViewMixin

Optionally used to allow more fine grained control over the query used to pull data. expandable_fields should be a dictionary of key = the field name that is expandable and val = a dict with the following keys.

  • join (optional): A table column to join() to the query.
  • outerjoin (optional): A table column to outerjoin() to the query.
  • options (optional): A list passed to the constructed queries’ options method. This is where you want to include the related objects to expand on. Without a value you here you will likely end up running lots of extra queries.

Example:

expandable_fields = {
    'author': {'join': Book.author, 'options': [joinedload(Book.author)]
}
expandable_fields = None

A dictionary of the fields can be expanded. Its definition is described above.

get_query()

If you override this method do not forget to call super().

pagination

class pyramid_restful.pagination.BasePagination

The base class each Pagination class should implement.

paginate_query(query, request)
Parameters:
  • query – SQLAlchemy query.
  • request – The request from the view
Returns:

The paginated date based on the provided query and request.

get_paginated_response(data)
Parameters:data – The paginated data.
Returns:A response containing the paginated data.
class pyramid_restful.pagination.PageNumberPagination

A simple page number based style that supports page numbers as query parameters.

For example:

http://api.example.org/accounts/?page=4
http://api.example.org/accounts/?page=4&page_size=100

page_size can be overridden as class attribute:

class MyPager(PageNumberPagination):
    page_size = 10

The resulting response JSON has four attributes, count, next, previous and results. Count indicates the total number of objects before pagination. Next and previous contain URLs that can be used to retrieve the next and previous pages of date respectively. The results attribute contains the list of objects that belong to page of data.

Example:

{
    'count': 50,
    'next': 'app.myapp.com/api/users?page=3',
    'previous': 'app.myapp.com/api/users?page=1',
    'results': [
        {id: 4, 'email': 'user4@myapp.com', 'name': 'John Doe'},
        {id: 5, 'email': 'user5@myapp.com', 'name': 'Jan Doe'}
    ]
}
paginate_query(query, request)
Parameters:
  • query – SQLAlchemy query.
  • request – The request from the view
Returns:

The paginated date based on the provided query and request.

get_paginated_response(data)
Parameters:data – The paginated data.
Returns:A response containing the paginated data.
get_url_root()

Override this if you need a different root url. For example if the app is behind a reverse proxy and you want to use the original host in the X-Forwarded-Host header.

class pyramid_restful.pagination.LinkHeaderPagination

Add a header field to responses called Link. The value of the Link header contains information about traversing the paginated resource. For more information about link header pagination checkout githhub’s great explanation: https://developer.github.com/v3/guides/traversing-with-pagination/

get_paginated_response(data)
Parameters:data – The paginated data.
Returns:A response containing the paginated data.