n6sdk.pyramid_commons

Note

Most of the classes defined in this module are not fully documented yet. For basic information how to use them (or at least most of them) – please consult the Tutorial.

class n6sdk.pyramid_commons.DefaultRootFactory(request)[source]

Bases: object

A Pyramid-URL-dispatch-related class.

Typically, when using n6sdk, you do not need to bother about it.

class n6sdk.pyramid_commons.StreamResponse(data_generator, renderer_name, request)[source]

Bases: pyramid.response.Response

A response class used to serve streamed HTTP responses to client queries.

Constructor args/kwargs:
data_generator:
An iterator/generator (being a data backend API’s method call result) that yields subsequent result dictionaries.
renderer_name:
The name of the stream renderer to be used to render the response (e.g., 'json'). The renderer should have been registered – see the documentation of register_stream_renderer().
request:
A Pyramid request object.
class n6sdk.pyramid_commons.DefaultStreamViewBase(*args, **kwargs)[source]

Bases: object

resource_id = None
renderers = None
data_spec = None
data_backend_api_method = None
adjust_exc = None
break_on_result_cleaning_error = True

This flag can be set to False in a subclass to skip result records that could not be cleaned. By default (when it is set to True), an error is raised if a result record could not be cleaned (then, typically, the final outcome is discontinuation of the – already partially sent – response).

classmethod concrete_view_class(resource_id, renderers, data_spec, data_backend_api_method, adjust_exc)[source]

Create a concrete view subclass (for a particular REST API resource).

This method is called automatically (by HttpResource.configure_views()).

Args/kwargs:
resource_id (string):
The identifier of the HTTP resource (as given as the resource_id argument for the HttpResource costructor).
renderers (frozenset of strings):
Names of available stream renderers (each of them should have been registered – see the documentation of register_stream_renderer()).
data_spec (instance of a BaseDataSpec subclass):
The data spec object used to validate and adjust query parameters and output data.
data_backend_api_method (string):
The name of a data backend API method to be called by the view.
adjust_exc (callable object):

A callable that will be called when an exception (derived from Exception) occurs during response generation. The callable must take one argument: an instance of Exception (or of its subclass). The callable must return any exception object – it can be either a new exception or the given exception object (possibly somewhat enriched).

Note

Typically the callable is ConfigHelper.exc_to_http_exc() (for details, see the source code of: HttpResource.configure_views(), ConfigHelper.complete() and ConfigHelper.exc_to_http_exc()).

Returns:
A concrete subclass of the class.
Raises:
ValueError:
If any of the renderers has not been registered.
TypeError:
If data_spec is a class and not an instance of a data specification class.
prepare_params()[source]
iter_deduplicated_params()[source]
call_api()[source]
call_api_method(api_method)[source]
get_clean_param_dict_kwargs()[source]
get_clean_result_dict_kwargs()[source]
get_extra_api_kwargs()[source]
class n6sdk.pyramid_commons.HttpResource(resource_id, url_pattern, renderers, data_spec, data_backend_api_method, view_base=<class 'n6sdk.pyramid_commons.DefaultStreamViewBase'>, http_methods=('GET', ), permission='dummy_permission', **kwargs)[source]

Bases: object

A class of containers of REST API resource properties.

Required constructor arguments (all of them are keyword-only!):
resource_id (string):
The identifier of the HTTP resource. It will be used as the Pyramid route name.
url_pattern (string):
A URL path pattern ending with the .{renderer} placeholder. Example value: "/some-url-path/incidents.{renderer}".
renderers (string or iterable of strings):
Names of available stream renderers (each of them should have been registered – see the documentation of register_stream_renderer()). Example value: ("json", "sjson").
data_spec (instance of a BaseDataSpec subclass):
The data specification object used to validate and adjust query parameters and output data.
data_backend_api_method (string):
The name of the data backend api method to be called by the view.
Optional constructor arguments (all of them are keyword-only!):
view_base (DefaultStreamViewBase subclass):
The base class of the view; default: DefaultStreamViewBase.
http_methods (string or iterable of strings):
Names of HTTP methods enabled for the resource; default: tuple ('GET',).
parmission:
An object representing a Pyramid permission; default: string "dummy_permission".
configure_views(config, adjust_exc)[source]

Automatically called by ConfigHelper.make_wsgi_app() or ConfigHelper.complete().

class n6sdk.pyramid_commons.ConfigHelper(settings, data_backend_api_class, authentication_policy, resources, static_view_config=None, root_factory=None, **rest_configurator_kwargs)[source]

Bases: object

Class of an object that automatizes necessary WSGI app setup steps.

Typical usage in your Pyramid application’s __init__.py:

RESOURCES = <list of HttpResource instances>

def main(global_config, **settings):
    helper = ConfigHelper(
        settings=settings,
        data_backend_api_class=MyDataBackendAPI,
        authentication_policy=MyCustomAuthenticationPolicy(settings),
        resources=RESOURCES,
    )
    ...  # <- here you can call any methods of the helper.config object
    ...  #    which is a pyramid.config.Configurator instance
    return helper.make_wsgi_app()

Note: all constructor arguments should be specified as keyword arguments.

default_static_view_config = None

(overridable attribute)

default_root_factory

(overridable attribute)

alias of DefaultRootFactory

make_wsgi_app()[source]
prepare_settings(settings)[source]
make_config()[source]
prepare_config(config)[source]
make_data_backend_api()[source]
complete()[source]
classmethod exception_view(exc, request)[source]
classmethod exc_to_http_exc(exc)[source]

Takes any Exception instance, returns a pyramid.httpexceptions.HTTPException instance.

n6sdk.pyramid_commons.register_stream_renderer(name, renderer_factory=None, allow_replace=False)[source]

Register a stream renderer factory under the specified name.

Args:
name (str):
The name of the renderer.
renderer_factory (callable object):
A callable that takes two positional arguments: data_generator and request (see the documentation of StreamResponse for the description of them), and returns a stream renderer. Stream renderer is an iterable that yields consecutive parts of the response for WSGI’s app_iter(). It is different than Pyramid renderers.
allow_replace (bool; default: False):
If set to true you can replace a renderer factory with another one.
Raises:
RuntimeError:
If name has been already used and allow_replace is not true.

Basic usage:

register_stream_renderer(<renderer name>, <renderer factory>)

or:

@register_stream_renderer(<renderer name>)
def make_my_renderer(data_generator, request):
    ...

or:

@register_stream_renderer(<renderer name>)
class MyRenderer(...):
    def __init__(self, data_generator, request):
        ...
    ...
class n6sdk.pyramid_commons.BaseAuthenticationPolicy[source]

Bases: object

The base class for authentication policy classes.

See: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/security.html#creating-your-own-authentication-policy

unauthenticated_userid(request)[source]
static get_auth_data(request)[source]

Determines the value that will be set as the auth_data of the request object.

This function is used as a request method that provides the auth_data request attribute (see: ConfigHelper.prepare_config() above), which means that this function is called after unauthenticated_userid() and before meth:`authenticated_userid.

It should be implemented as a static method.

Concrete implementation of this method will probably make use of the unauthenticated_userid attribute of request (in older versions of Pyramid the unauthenticated_userid() function from the pyramid.security module was used instead of that attribute).

Returns:
Authentication data (in an application-specific format). The default implementation returns None.
authenticated_userid(request)[source]

Concrete implementation of this method will probably make use of the auth_data attribute of request. (The value of that attribute is produced by the get_auth_data() method.)

effective_principals(request)[source]
forget(request)[source]

Can be left dummy if users are recognized externally, e.g. by SSL cert.

remember(request, principal, **kw)[source]

Can be left dummy if users are recognized externally, e.g. by SSL cert.

class n6sdk.pyramid_commons.AnonymousAuthenticationPolicy[source]

Bases: n6sdk.pyramid_commons.BaseAuthenticationPolicy

A dummy authentication policy: authenticates everybody (as "anonymous").

It sets, for all requests, the user id and the authentication data to the string "anonymous".

unauthenticated_userid(request)[source]
static get_auth_data(request)[source]
authenticated_userid(request)[source]