tornadowebapi package

Submodules

tornadowebapi.authenticator module

class tornadowebapi.authenticator.Authenticator[source]

Bases: object

classmethod authenticate(handler)[source]

Performs authentication of the access

class tornadowebapi.authenticator.NullAuthenticator[source]

Bases: tornadowebapi.authenticator.Authenticator

Authenticator class for the web handlers that does nothing and returns None

classmethod authenticate(handler)[source]

Called by the handler to authenticate the user. The handler passes itself as an argument, and expects a valid handler.current_user value, or None.

Note that returning None does not mean that the API will reject the request. Just that the current_user is unrecognized. Individual Resources must then adapt their behavior according to this information

tornadowebapi.exceptions module

exception tornadowebapi.exceptions.BadRepresentation(message=None, **kwargs)[source]

Bases: tornadowebapi.exceptions.WebAPIException

Exception raised when the resource representation is invalid or does not contain the appropriate keys. Raise this exception in your handlers when the received representation is ill-formed

http_code = 400
exception tornadowebapi.exceptions.BadRequest(message=None, **kwargs)[source]

Bases: tornadowebapi.exceptions.WebAPIException

Deprecated. Kept for compatibility. Use BadRepresentation.

http_code = 400
exception tornadowebapi.exceptions.Exists(message=None, **kwargs)[source]

Bases: tornadowebapi.exceptions.WebAPIException

Represents a case where the resource could not be created because it already exists. This is generally raised in the create() method if the resource has uniqueness constraints on things other than the exposed id.

http_code = 409
representation()[source]

Exists does not have a representation, just an error status

exception tornadowebapi.exceptions.NotFound(message=None, **kwargs)[source]

Bases: tornadowebapi.exceptions.WebAPIException

Exception raised when the resource is not found. Raise this exception in your handlers when you can’t find the resource the identifier refers to.

http_code = 404
representation()[source]

NotFound is special as it does not have a representation, just an error status

exception tornadowebapi.exceptions.Unable(message=None, **kwargs)[source]

Bases: tornadowebapi.exceptions.WebAPIException

Exception raised when the request cannot be performed for whatever reason that is not dependent on the client.

http_code = 500
exception tornadowebapi.exceptions.WebAPIException(message=None, **kwargs)[source]

Bases: Exception

Base exception for the REST infrastructure These are exceptions that can be raised by the handlers.

http_code = 500

HTTP code generally associated to this exception. Missing any better info, default is a server error.

representation()[source]

Returns a dictionary with the representation of the exception.

tornadowebapi.handler module

class tornadowebapi.handler.BaseHandler(application, request, **kwargs)[source]

Bases: tornado.web.RequestHandler

api_version

Returns the API version this handler is taking care of

base_urlpath

Returns the Base urlpath as from initial setup

get_resource_handler_or_404(collection_name)[source]

Given a collection name, inquires the registry for its associated Resource class. If not found raises HTTPError(NOT_FOUND)

initialize(registry, base_urlpath, api_version)[source]

Initialization method for when the class is instantiated.

log
prepare()[source]

Runs before any specific handler.

registry

Returns the class vs Resource registry

to_http_exception(exc)[source]

Converts a REST exception into the appropriate HTTP one.

write_error(status_code, **kwargs)[source]

Provides appropriate payload to the response in case of error.

class tornadowebapi.handler.CollectionHandler(application, request, **kwargs)[source]

Bases: tornadowebapi.handler.BaseHandler

Handler for URLs addressing a collection.

get(collection_name)[source]

Returns the collection of available items

post(collection_name)[source]

Creates a new resource in the collection.

class tornadowebapi.handler.JSAPIHandler(application, request, **kwargs)[source]

Bases: tornadowebapi.handler.BaseHandler

Handles the JavaScript API request.

create_template_loader(template_path)[source]

Ovberride the default template loader, because if any code overrides the template loader in the settings, we don’t want to rely on that. We want to be sure we use the tornado loader.

get()[source]
get_template_path()[source]

Override the path to make sure we search relative to this file

class tornadowebapi.handler.ResourceHandler(application, request, **kwargs)[source]

Bases: tornadowebapi.handler.BaseHandler

Handler for URLs addressing a resource.

SUPPORTED_METHODS = ('GET', 'POST', 'PUT', 'DELETE')
delete(collection_name, identifier)[source]

Deletes the resource.

get(collection_name, identifier)[source]

Retrieves the resource representation.

post(collection_name, identifier)[source]

This operation is not possible in REST, and results in either Conflict or NotFound, depending on the presence of a resource at the given URL

put(collection_name, identifier)[source]

Replaces the resource with a new representation.

tornadowebapi.registry module

class tornadowebapi.registry.Registry[source]

Bases: object

api_handlers(base_urlpath, version='v1')[source]

Returns the API handlers for the interface. Add these handlers to your application to provide an interface to your Resources.

Parameters:
  • base_urlpath (str) – The base url path to serve
  • version (str) – A string identifying the version of the API.

Notes

The current implementation does not support multiple API versions yet. The version option is only provided for futureproofing.

authenticator
register(typ, collection_name=None)[source]

Registers a Resource type with an appropriate collection name. A collection name is a pluralized version of the resource, created by lowercasing the class name and adding an “s”. The resulting collection name will be used in the URL representing the resource. For example, a resource Image will have URLs of the type

http://example.com/api/v1/images/identifier/

The collection name can always be overridden by specifying __collection_name__ in the resource class, or by specifying the collection_name parameter.

Parameters:
  • typ (Resource) – A subclass of the rest Resource type
  • collection_name (str or None) – Overrides the resource collection name.
Raises:

TypeError: – if typ is not a subclass of Resource

registered_types
tornadowebapi.registry.registry = <tornadowebapi.registry.Registry object>

global registry for registration of the classes.

tornadowebapi.resource module

class tornadowebapi.resource.Resource(application, current_user)[source]

Bases: object

Base class for resources. To implement a new Resource class, inherit from this subclass and reimplement the CRUD class methods with the appropriate logic.

The Resource exports two member vars: application and current_user. They are equivalent to the members in the tornado web handler.

create(representation)[source]

Called to create a resource with a given representation The representation is a dictionary containing keys. The reimplementing code is responsible for checking the validity of the representation. Correspond to a POST operation on the resource collection.

Parameters:

representation (dict) – A dictionary containing the representation as from the HTTP request.

Returns:

id – An identifier identifying the newly created resource. It must be unique within the collection.

Return type:

str

Raises:
  • Exists: – Raised when the resource cannot be created because of a conflicting already existing resource.
  • BadRepresentation: – Raised when the representation does not validate according to the resource expected representation.
  • NotImplementedError: – If the resource does not support the method.
delete(identifier)[source]

Called to delete a specific resource given its identifier. Corresponds to a DELETE operation on the resource URL.

Parameters:

identifier (str) – A string identifying the resource

Returns:

Return type:

None

Raises:
  • NotFound: – Raised if the resource with the given identifier cannot be found
  • NotImplementedError: – If the resource does not support the method.
exists(identifier)[source]

Returns True if the resource with a given identifier exists. False otherwise.

Parameters:identifier (str) – A string identifying the resource
Returns:bool
Return type:True if found, False otherwise.
items()[source]

Invoked when a request is performed to the collection URL. Returns a list of identifiers available. Corresponds to a GET operation on the collection URL.

Returns:list
Return type:The list of available identifiers.
Raises:NotImplementedError: – If the resource collection does not support the method.

Notes

For security reasons stemming from cross site execution, this list will not be rendered as a list in a json representation. Instead, a dictionary with the key “items” and value as this list will be returned.

retrieve(identifier)[source]

Called to retrieve a specific resource given its identifier. Correspond to a GET operation on the resource URL.

Parameters:

identifier (str) – A string identifying the resource

Returns:

representation – a dict representation of the resource.

Return type:

dict

Raises:
  • NotFound: – Raised if the resource with the given identifier cannot be found
  • NotImplementedError: – If the resource does not support the method.
update(identifier, representation)[source]

Called to update a specific resource given its identifier with a new representation. The method is responsible for validating the representation content. Correspond to a PUT operation on the resource URL.

Parameters:
  • identifier (str) – A string identifying the resource
  • representation (dict) – a dict representation of the resource.
Returns:

Return type:

None

Raises:
  • NotFound: – Raised if the resource with the given identifier cannot be found
  • BadRepresentation: – Raised when the representation does not validate according to the resource expected representation.
  • NotImplementedError: – If the resource does not support the method.
validate_identifier(identifier)[source]

Validates the identifier from a request. Any exception occurring in this method will be converted into a NotFound exception. Exceptions that belong to this distribution will be let through to produce the expected response.

Note: We use NotFound (404) because the URL is likely valid. If our identifiers are all integers, so that

/foo/1/

is a valid URL for identifier 1, and the following url

/foo/whatever/

Is simply not present.

This method is always called before being dispatched to the CRUD methods accepting an identifier. By default, it does nothing, accepts any identifier, and returns the same identifier.

The method can also be used to modify the incoming identifier so that it’s compliant with the expectations, or return a new identifier.

Returns:
Return type:The identifier that will be used.
validate_representation(representation)[source]

Validates the representation incoming from a request, after it has been decoded. Any generic exception occurring in this method will be converted into a BadRepresentation exception. Exceptions that belong to this distribution will be let through to produce the expected response.

This method is always called before being dispatched to the CRUD methods accepting a representation. By default, it does nothing, accepts any representation, and returns the same representation.

The method can also be used to modify the incoming representation so that it’s compliant with the expectations, or return a new representation.

Returns:
Return type:The representation that will be used.

tornadowebapi.utils module

tornadowebapi.utils.url_path_join(*pieces)[source]

Join components of url into a relative url path Use to prevent double slash when joining subpath. This will leave the initial and final / in place

Assume pieces do not contain protocol (e.g. http://)

tornadowebapi.utils.with_end_slash(url)[source]

Normalises a url to have an ending slash, and only one.

Module contents

tornadowebapi.api_handlers(base_urlpath, version='v1')[source]

Returns the API handlers for the interface. Add these handlers to your application to provide an interface to your Resources.

Parameters:
  • base_urlpath (str) – The base url path to serve
  • version (str) – A string identifying the version of the API.

Notes

The current implementation does not support multiple API versions yet. The version option is only provided for futureproofing.