aiida.restapi.common package

Submodules

aiida.restapi.common.config.APP_CONFIG = {'DEBUG': False, 'PROPAGATE_EXCEPTIONS': True}

JSON serialization config. Leave this dictionary empty if default Flask serializer is desired.

Here is a list a all supported fields. If a field is not present in the dictionary its value is assumed to be ‘default’.

DATETIME_FORMAT: allowed values are ‘asinput’ and ‘default’.

aiida.restapi.common.config.CACHING_TIMEOUTS = {'calculations': 10, 'codes': 10, 'computers': 10, 'datas': 10, 'groups': 10, 'nodes': 10, 'users': 10}

Schema customization (if file schema_custom.json is present in this same folder)

aiida.restapi.common.config.MAX_TREE_DEPTH = 5

Aiida profile used by the REST api when no profile is specified (ex. by –aiida-profile flag). This has to be one of the profiles registered in .aiida/config.json

In case you want to use the default stored in .aiida/config.json, set this varibale to “default”

aiida.restapi.common.config.PREFIX = '/api/v2'

Flask app configs.

DEBUG: True/False. enables debug mode N.B. !!!For production run use ALWAYS False!!!

PROPAGATE_EXCEPTIONS: True/False serve REST exceptions to the client (and not a generic 500: Internal Server Error exception)

aiida.restapi.common.config.SERIALIZER_CONFIG = {'datetime_format': 'default'}

Caching configuration

memcached: backend caching system

This file contains the exceptions that are raised by the RESTapi at the highest level, namely that of the interaction with the client. Their specificity resides into the fact that they return a message that is embedded into the HTTP response.

Example:

…/api/v1/nodes/ … (TODO compete this with an actual example)

Other errors arising at deeper level, e.g. those raised by the QueryBuilder or internal errors, are not embedded into the HTTP response.

exception aiida.restapi.common.exceptions.RestFeatureNotAvailable[source]

Bases: aiida.common.exceptions.FeatureNotAvailable

__module__ = 'aiida.restapi.common.exceptions'
exception aiida.restapi.common.exceptions.RestInputValidationError[source]

Bases: aiida.common.exceptions.InputValidationError

document with an example

__module__ = 'aiida.restapi.common.exceptions'
exception aiida.restapi.common.exceptions.RestValidationError[source]

Bases: aiida.common.exceptions.ValidationError

document with an example

__module__ = 'aiida.restapi.common.exceptions'
class aiida.restapi.common.utils.CustomJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None)[source]

Bases: flask.json.JSONEncoder

Custom json encoder for serialization. This has to be provided to the Flask app in order to replace the default encoder.

__module__ = 'aiida.restapi.common.utils'
default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    return JSONEncoder.default(self, o)
class aiida.restapi.common.utils.Utils(**kwargs)[source]

Bases: object

A class that gathers all the utility functions for parsing URI, validating request, pass it to the translator, and building HTTP response

An istance of Utils has to be included in the api class so that the configuration parameters used to build the api are automatically accessible by the methods of Utils without the need to import them from the config.py file.

__dict__ = dict_proxy({'split_path': <function split_path>, '__module__': 'aiida.restapi.common.utils', 'parse_query_string': <function parse_query_string>, 'build_datetime_filter': <function build_datetime_filter>, 'strip_prefix': <function strip_prefix>, 'paginate': <function paginate>, 'build_response': <function build_response>, 'build_translator_parameters': <function build_translator_parameters>, 'validate_request': <function validate_request>, 'build_headers': <function build_headers>, 'parse_path': <function parse_path>, '__dict__': <attribute '__dict__' of 'Utils' objects>, 'op_conv_map': {'=like=': 'like', '=ilike=': 'ilike', '>=': '>=', '=in=': 'in', '<': '<', '!=': '!==', '<=': '<=', '=': '==', '=notin=': '!in', '>': '>'}, '__weakref__': <attribute '__weakref__' of 'Utils' objects>, '__doc__': '\n A class that gathers all the utility functions for parsing URI,\n validating request, pass it to the translator, and building HTTP response\n\n An istance of Utils has to be included in the api class so that the\n configuration parameters used to build the api are automatically\n accessible by the methods of Utils without the need to import them from\n the config.py file.\n\n ', '__init__': <function __init__>})
__init__(**kwargs)[source]

Sets internally the configuration parameters

__module__ = 'aiida.restapi.common.utils'
__weakref__

list of weak references to the object (if defined)

build_datetime_filter(dt)[source]

This function constructs a filter for a datetime object to be in a certain datetime interval according to the precision.

The interval is [reference_datetime, reference_datetime + Dt], where Dt is a function fo the required precision.

This function should be used to replace a datetime filter based on the equality operator that is inehrently “picky” because it implies matching two datetime objects down to the microsecond or something, by a “tolerant” operator which checks whether the datetime is in an interval.

Returns:a suitable entry of the filter dictionary
build_headers(rel_pages=None, url=None, total_count=None)[source]

Construct the header dictionary for an HTTP response. It includes related pages, total count of results (before pagination).

Parameters:
  • rel_pages – a dictionary defining related pages (first, prev, next, last)
  • url – (string) the full url, i.e. the url that the client uses to get Rest resources
build_response(status=200, headers=None, data=None)[source]

Build the response

Parameters:
  • status – status of the response, e.g. 200=OK, 400=bad request
  • headers – dictionary for additional header k,v pairs, e.g. X-total-count=<number of rows resulting from query>
  • data – a dictionary with the data returned by the Resource
Returns:

a Flask response object

build_translator_parameters(field_list)[source]

Takes a list of elements resulting from the parsing the query_string and elaborates them in order to provide translator-compliant instructions

Parameters:field_list – a (nested) list of elements resulting from parsing the query_string
Returns:the filters in the
op_conv_map = {'!=': '!==', '<': '<', '<=': '<=', '=': '==', '=ilike=': 'ilike', '=in=': 'in', '=like=': 'like', '=notin=': '!in', '>': '>', '>=': '>='}
paginate(page, perpage, total_count)[source]

Calculates limit and offset for the reults of a query, given the page and the number of restuls per page. Moreover, calculates the last available page and raises an exception if the required page exceeds that limit. If number of rows==0, only page 1 exists :param page: integer number of the page that has to be viewed :param perpage: integer defining how many results a page contains :param total_count: the total number of rows retrieved by the query :return: integers: limit, offset, rel_pages

parse_path(path_string, parse_pk_uuid=None)[source]

Takes the path and parse it checking its validity. Does not parse “io”, “content” fields. I do not check the validity of the path, since I assume that this is done by the Flask routing methods.

Parameters:
  • path_string – the path string
  • parse_id_uuid – if ‘pk’ (‘uuid’) expects an integer (uuid starting pattern)
Returns:

resource_type (string) page (integer) id (string: uuid starting pattern, int: pk) query_type (string))

parse_query_string(query_string)[source]

Function that parse the querystring, extracting infos for limit, offset, ordering, filters, attribute and extra projections. :param query_string (as obtained from request.query_string) :return: parsed values for the querykeys

split_path(path)[source]
Parameters:path – entire path contained in flask request
Returns:list of each element separated by ‘/’
strip_prefix(path)[source]

Removes the PREFIX from an URL path. PREFIX must be defined in the config.py file:

PREFIX = "/api/v2"
path = "/api/v2/calculations/page/2"
strip_prefix(path) ==> "/calculations/page/2"
Parameters:path – the URL path string
Returns:the same URL without the prefix
validate_request(limit=None, offset=None, perpage=None, page=None, query_type=None, is_querystring_defined=False)[source]

Performs various checks on the consistency of the request. Add here all the checks that you want to do, except validity of the page number that is done in paginate(). Future additional checks must be added here

class aiida.restapi.common.utils.datetime_precision(dt, precision)[source]

A simple class which stores a datetime object with its precision. No internal check is done (cause itis not possible).

precision: 1 (only full date)
2 (date plus hour) 3 (date + hour + minute) 4 (dare + hour + minute +second)
__init__(dt, precision)[source]
__module__ = 'aiida.restapi.common.utils'
aiida.restapi.common.utils.list_routes()[source]

List available routes