API

Configuration

pyramid_resourceful.config.add_json_adapter(self: pyramid.config.Configurator, adapter)

Add a JSON adapter.

pyramid_resourceful.config.add_json_adapters(self: pyramid.config.Configurator, *adapters)

Add default and additional JSON adapters.

Adds default JSON adapters for date, datetime, and decimal objects:

  • date -> ISO date string

  • datetime -> ISO datetime string

  • decimal -> string

Also adds additional adapters if specified.

Note

If you don’t want the defaults, use add_json_adapter() instead.

pyramid_resourceful.config.add_resource(self: pyramid.config.Configurator, resource_class, resource_args=None, resource_factory=None, name=None, renderers=['json'], allowed_methods=None, acl=<pyramid_resourceful.util.NOT_SET object>, path=None, segments=(), route_args=None, view=<class 'pyramid_resourceful.view.ResourceView'>, permission=None, view_args=None, name_prefix=None, path_prefix=None) pyramid_resourceful.config.AddResourceInfo

Add routes and views for a resource.

Given a resource (class), generates a set of routes and associated views.

Args:
resource_class: The class that implements the resource. This

must accept the current request as its first arg. It may also accept other args…

resource_args: Args that will be passed to the resource factory

to construct a configured instance of the resource.

resource_factory: The factory that will be used to create an

instance of resource_class for the current request. If this isn’t specified, the resource_class itself will be used as the factory.

name: The base route name. If not specified, this will be

generated from the resource class’s module path and class name as follows:

  • If the class name ends with “Resource”, that’s stripped off

  • The class name is then converted to snake case

  • The module name containing the class is joined to the converted class name with a dot

So, for a resource class named ContainerResource in a module named api, the computed name will be “api.container”.

renderers: A list of renderers to generate routes and views for.

This can include entries like “json” and/or “template.mako”.

For each renderer, a route with an extension (like “.json” and/or “.html”) is generated with a view for each corresponding resource method. In this case, the response is rendered according to the extension.

In addition, a route with no extension is generated with a view for each corresponding resource method. In this case, the response is rendered according to the Accept header in the request.

allowed_methods: The HTTP methods that are allowed on the

resource being configured. This is usually derived from the methods defined on the resource_class. An allowed_methods attribute will be added resource instances that don’t already have one.

acl: An ACL list that will be attached to resource instances as

the``__acl__`` attribute. If this isn’t specified and the resource class doesn’t have an __acl__ attribute already, the default ACL will be attached instead (assuming a default ACL is configured).

path: The base route path. If not specified, this will be

computed from name by replacing dots with slashes and underscores with dashes. For the example above, the computed path would be “/api/container”.

path_prefix: If specified, this will be prepended to all

generated route paths.

segments (str|list): Additional path segments to join to

the base route path. Examples (assuming path="/path"):

  • segments=”{id}” -> “/path/{id}”

  • segments=(“{a}”, “{b}”) -> “/path/{a}/{b}”

  • segments=”{a}/{b}” -> “/path/{a}/{b}”

  • segments=”{c:.+} -> “/path/{c:.+}”

This is useful when an explicit path isn’t passed (and is therefore computed from the resource name). As shown in the last example, a regular expression can be included as well.

Note

All of the segments must be relative paths–they should not start with slashes.

route_args: Common route args that will be passed to every

call to config.add_view().

view: The view class that will call methods on the resource

class. This is optional because in many cases the included/ default view class will suffice.

permission: Permission that will be set on all generated views.

This is a special case for convenience.

view_args: Common view args that will be passed to every call

to config.add_view().

name_prefix: If specified, this will be prepended to all

generated route names (separated by a dot).

Note

This is generally not used directly.

path_prefix: If specified, this will be prepended to all

generated route paths (separated by a forward slash).

Note

This is generally not used directly.

Settings can be set under the “pyramid_resourceful” key:

  • default_acl: Default ACL to attach to resource classes that don’t have an __acl__ attribute (when acl isn’t specified).

  • resource_methods: Methods on resource classes that will be considered resource methods (these should be lower case); if not specified, the default RESOURCE_METHODS will be used.

pyramid_resourceful.config.add_resources(self: pyramid.config.Configurator, name_prefix=None, path_prefix=None, resource_args=None, add_method=None, **add_kwargs)

Add multiple resources with the same base configuration.

This can be used to add a set of resources under a common name and/or path prefix. For example, this sets the name prefix to “api”, which will cause all the route names to be prefixed with “api.” and all the route paths to be prefixed with “/api”:

with config.add_resources("api") as add_resource:
    add_resource(".resources.ContainerResource")
    # name -> api.resources.container
    # path -> /api/resources/container

    add_resource(".resources.ItemResource")
    # name -> api.resources.item
    # path -> /api/resources/item

If the resources have other shared configuration, the common args can be passed in too. For example, to specify the same permission for a set of resources/views:

with config.add_resources("api", permission="admin") as api:
    api(".resources.ContainerResource")
    api(".resources.ItemResource")
pyramid_resourceful.config.enable_cors(self: pyramid.config.Configurator)

Enable CORS permissively (for use in development).

This allows CORS requests from anywhere, which is probably not what you want, other than in development.

Warning

Use with CAUTION. See add_cors_headers() for additional info.

pyramid_resourceful.config.enable_post_tunneling(self: pyramid.config.Configurator, allowed_methods=('DELETE', 'PATCH', 'PUT'), param_name='$method', header_name='X-HTTP-Method-Override')

Allow other request methods to be tunneled via POST.

This allows DELETE, PATCH, and PUT and requests to be tunneled via POST requests. The method can be specified using a parameter or a header.

The name of the parameter is “$method”; it can be a query or POST parameter. The query parameter will be preferred if both the query and POST parameters are present in the request.

The name of the header is “X-HTTP-Method-Override”. If the parameter described above is passed, this will be ignored.

The request method will be overwritten before it reaches application code, such that the application will never be aware of the original request method. Likewise, the parameter and header will be removed from the request, and the application will never see them.

Settings

pyramid_resourceful.settings.DEFAULT_SETTINGS = {'default_acl': <pyramid_resourceful.util.NOT_SET object>, 'get_default_response_fields': None, 'item_processor': None, 'resource_methods': ('delete', 'get', 'options', 'patch', 'post', 'put')}

Default settings.

These defaults can be overridden by setting the corresponding keys in the project’s settings under the “pyramid_resourceful” key like so:

>>> settings = {}
>>> set_setting(settings, "resource_methods", ["get"])

.. note:: There's no facility for reading settings from a config
    file at this time.
pyramid_resourceful.settings.get_setting(all_settings, name, default=<pyramid_resourceful.util.NOT_SET object>)

Get pyramid_resourceful setting from config.

If the setting wasn’t set in the app, the passed default value will be used. If a default value wasn’t passed, the default from DEFAULT_SETTINGS will be used.

pyramid_resourceful.settings.set_setting(all_settings, name, value) Any

Set a pyramid_resourceful setting.

This ensures the top level pyramid_resourceful key exists in the settings, checks that name is a valid setting name, converts the setting value according to its defined type, and returns the converted value.

Views

class pyramid_resourceful.view.ResourceView(context, request: pyramid.request.Request)
get_standard_response(data)

Get a standard response.

When there’s no data, return a 204 No Content response regardless of the request method or configured renderers. Otherwise…

For XHR requests, return a 200 OK response with rendered data for all request methods (typically JSON).

For non-XHR requests:

  • Return a 200 OK response with rendered data for GET requests (typically HTML rendered from a template). For HEAD requests, the data is also returned so that Pyramid can generate a HEAD response.

  • Return a 303 See Other response for DELETE, PATCH, PUT, and POST requests:

    • For DELETEs, use the referrer if it’s safe (same origin) or fall back to the URL of the current resource.

    • For other methods, fall back to the URL of the current resource (which is always safe).

Resources

pyramid_resourceful.resource.resource_config(**view_args)

Specify resource config on resource method.

Currently, all of the supplied keyword args will be passed through to Pyramid’s Configurator.add_view(). At some point, other resource-oriented config options might be added.

class pyramid_resourceful.resource.Resource(request: pyramid.request.Request)

Utilities

pyramid_resourceful.util.extract_data(request)

Extract request data from form or JSON data.

Note

Blank form data values will be converted to None. This applies only to data posted from HTML forms. JSON data is left as is.

pyramid_resourceful.util.get_param(request, name, converter=None, params=None, *, multi=False, strip=False, convert_blank_to_none=True, default=<pyramid_resourceful.util.NOT_SET object>) Union[Any, List[Any]]

Get the specified request parameter and, optionally, convert it.

Args:
params: Any dict-like object that also has getone and

getall methods. Defaults to request.GET.

multi (bool): If set, all params with name will be collected

into a list (even if there’s only one such param). If not set, only one param with name may be present in params.

strip (bool): If set, param values will be stripped before being

converted.

convert_blank_to_none (bool): If set, blank param values will be

converted to None. Blank param values look like a=.

converter (callable): If specified, the value or values will be

passed to this callable for conversion (unless converted the value was already converted to None). If a value can’t be parsed, a 400 exception response will be raised.

default (any): A default value to return when the param isn’t

present. If the param isn’t present and no default value is specified, a KeyError will be raised.

Returns:

any: When multi is not set list[any]: When multi is set

Raises:

KeyError: Param isn’t present and no default value is given. KeyError: multi=False but param is present multiple times. 400 response: Param value can’t be converted by converter.

Special handling of flag parameters:

If converter is bool or as_bool() and the param is specified only once and the param has no value, the param will be handled as a flag. Note that in this example, c is not considered a flag due to the equal sign (it has a blank value):

>>> from pyramid.request import Request
>>> req = Request.blank("/endpoint?a&!b&c=")
>>> get_param(req, "a", bool) -> True
>>> get_param(req, "b", bool) -> False

SQLAlchemy Resource Types

class pyramid_resourceful.sqlalchemy.SQLAlchemyResource(request, model=None, key=None, base_query=None, joined_load_with=None, filters_to_skip=None, filter_converters=None, **kwargs)

Base for SQLAlchemy resource types.

Args:

request: The current request.

model: SQLAlchemy ORM class.

key: Key used to refer to item or items in returned data.

base_query: Base SQLAlchemy query. If not specified, this will be

set to request.dbsession.query(model).

joined_load_with: Entities to load in the same query. Note that

func:sqlalchemy.orm.joinedload is used to load these entities. For complex query logic, this might not be suitable.

filters_to_skip: Filters that should be skipped by

apply_filters(). The intent behind this is to specify filters which will be handled specially rather than by the default filtering logic.

filter_converters (dict): A mapping of filter names to converter

functions. These are used to convert filter values before they’re used to filter a query. For example, this can be used to convert date strings to date objects.

apply_filters(q, *, skip_filters=())

Get filters and apply them to the base query.

See get_filters() for how filters are specified. By default, filters are ANDed together. This can be overridden by specifying $operator=or in the request’s parameters.

apply_options(q)

Apply options to query.

convert_filters(filters, converters)

Convert filter values.

extract_fields(item, fields=None)

Extract fields from item.

The incoming item is typically an ORM instance and the returned item is typically a dict.

get_default_response_fields(item)

Get default fields to include in response.

get_filters(*, params=None, converter=<function loads>)

Get filters from request.

get_response_fields(item)

Get fields to include in response.

By default, all column attributes will be included. To include additional fields:

field=*&field=x&field=y&field=z

The default fields plus x, y, and z will be included.

To specify only some fields:

field=a&field=b&field=c

Only fields a, b, and c will be included.

Fields can be passed via one or more field request parameters or via a single fields request parameter formatted as a comma-separated list. These are equivalent:

field=a&field=b&field=c
fields=a,b,c
process_item(item)

Process item after fields have been extracted.

The incoming item is typically a dict. By default, the item is returned as is.

class pyramid_resourceful.sqlalchemy.SQLAlchemyContainerResource(request, model=None, key=None, base_query=None, joined_load_with=None, filters_to_skip=None, filter_converters=None, item_key=None, filtering_enabled=None, filtering_supported_operators=None, ordering_enabled=None, ordering_default=None, pagination_enabled=None, pagination_default_page_size=None, pagination_max_page_size=None)

SQLAlchemy container resource.

Provides the following methods:

  • get -> Get all or a filtered subset of items

  • post -> Add a new item

get(*, wrapped=True)

Get items in container.

get_filters(*, params=None, converter=<function loads>)

Get filters from request.

The filters query parameter is a JSON-encoded object containing filter specifications using one of the following formats:

1. "column": <value>
2. "column [operator]": <value>

In the first case, the operator will be = if the value is a scalar or in if the value is a list.

For the second case, see the list of allowed operators defined by attr:filtering_supported_operators.

Example:

?filters={"a": 1, "b": ["1", "2"], "c <": 4}

This is converted to:

a = 1 and b in ('1', '2') and c < 4

Note

Filters are extracted from request.GET by default. Pass a different source via params if necessary (see get_params() for more details).

post()

Add item to container.

class pyramid_resourceful.sqlalchemy.SQLAlchemyItemResource(request, model=None, key=None, base_query=None, joined_load_with=None, filters_to_skip=None, filter_converters=None, **kwargs)

SQLAlchemy item resource.

Provides the following methods:

  • delete -> Delete item

  • get -> Get item

  • patch -> Update some fields on item

  • put -> Create or update item

delete()

Delete item.

get(*, wrapped=True)

Get item.

get_filters(*, params=None)

Get filters from request.

patch()

Update select fields on item.

put()

Create or update item.

If an item with the specified identifier exists, it will updated. Otherwise, a new item will be created.