tmserver package

Module contents

Submodules

tmserver.appfactory module

tmserver.appfactory.create_app(verbosity=None)

Creates a Flask application object that registers all the blueprints on which the actual routes are defined.

Parameters:

verbosity: int, optional

logging verbosity to override the logging_verbosity setting in the configuration file (default: None)

Returns:

flask.Flask

Flask application

tmserver.config module

class tmserver.config.ServerConfig

Bases: tmlib.config.TmapsConfig

TissueMAPS configuration specific to the tmserver package.

jwt_expiration_delta

datetime.timedelta: time interval until JSON web token expires (default: datetime.timedelta(hours=6))

logging_verbosity

int: verbosity level for loggers (default: 2)

secret_key

str: secret key (default: "default_secret_key")

tmserver.error module

Custom exception types and associated serializers. When raised these exceptions will be automatically handled and serialized by the flask error handler and sent to the client.

exception tmserver.error.ForbiddenError(message='User is not authorized to access requested resource.')

Bases: tmserver.error.HTTPException

exception tmserver.error.HTTPException(message, status_code)

Bases: exceptions.Exception

exception tmserver.error.MalformedRequestError(message='Invalid request')

Bases: tmserver.error.HTTPException

exception tmserver.error.MissingGETParameterError(*parameters)

Bases: tmserver.error.MalformedRequestError

exception tmserver.error.MissingPOSTParameterError(*parameters)

Bases: tmserver.error.MalformedRequestError

exception tmserver.error.MissingPUTParameterError(*parameters)

Bases: tmserver.error.MalformedRequestError

exception tmserver.error.NotAuthorizedError(message='User cannot access the requested resource.')

Bases: tmserver.error.HTTPException

exception tmserver.error.ResourceNotFoundError(model, **parameters)

Bases: tmserver.error.HTTPException

tmserver.error.encode_api_exception(obj, encoder)
tmserver.error.handle_error(error)
tmserver.error.register_http_error_classes(app)

Registers an error handler for error classes derived from HTTPException.

Parameters:

error_handler: function

blueprint-specific error handler

tmserver.serialize module

Serialization mechanism for TissueMAPS database model objects.

class tmserver.serialize.TmJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)

Bases: flask.json.JSONEncoder

Custom JSON encoder to serialize types defined for TissueMAPS. This serializer will also check supertypes if no matching serializer was found. Serializers need to be registered with the json_encoder decorator:

@json_encoder(SomeClass)
def encode_some_class(obj, encoder):
    return {
        'id': encode_pk(obj.id)
        ...
    }

Make sure that the files where the serializers are defined are imported at application start, otherwise they won’t be registered.

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. None (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8.

If use_decimal is true (default: True), decimal.Decimal will be supported directly by the encoder. For the inverse, decode JSON with parse_float=decimal.Decimal.

If namedtuple_as_object is true (the default), objects with _asdict() methods will be encoded as JSON objects.

If tuple_as_array is true (the default), tuple (and subclasses) will be encoded as JSON arrays.

If iterable_as_array is true (default: False), any object not in the above table that implements __iter__() will be encoded as a JSON array.

If bigint_as_string is true (not the default), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise.

If int_as_string_bitcount is a positive number (n), then int of size greater than or equal to 2**n or lower than or equal to -2**n will be encoded as strings.

If specified, item_sort_key is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key.

If for_json is true (not the default), objects with a for_json() method will use the return value of that method for encoding as JSON instead of the object.

If ignore_nan is true (default: False), then out of range float values (nan, inf, -inf) will be serialized as null in compliance with the ECMA-262 specification. If true, this will override allow_nan.

default(obj)

Overridden serializer function invoked by flask

tmserver.serialize.encode_acquisition(obj, encoder)
tmserver.serialize.encode_channel(obj, encoder)
tmserver.serialize.encode_channel_layer(obj, encoder)
tmserver.serialize.encode_cycle(obj, encoder)
tmserver.serialize.encode_experiment(obj, encoder)
tmserver.serialize.encode_feature(obj, encoder)
tmserver.serialize.encode_mapobject_type(obj, encoder)
tmserver.serialize.encode_microscope_image_file(obj, encoder)
tmserver.serialize.encode_microscope_metadata_file(obj, encoder)
tmserver.serialize.encode_plate(obj, encoder)
tmserver.serialize.encode_plot(obj, encoder)
tmserver.serialize.encode_segmentation_layer(obj, encoder)
tmserver.serialize.encode_site(obj, encoder)
tmserver.serialize.encode_tool_result(obj, encoder)
tmserver.serialize.encode_well(obj, encoder)
tmserver.serialize.enocode_microscope_image_file(obj, encoder)
tmserver.serialize.enocode_microscope_metadata_file(obj, encoder)
tmserver.serialize.json_encoder(obj_type)

Decorator for functions that JSON serialiaze objects.

tmserver.util module

Various utility functions used by view functions and other parts of the server application.

tmserver.util.assert_form_params(*params)

A decorator for POST request functions that asserts that the form body contains the required parameters.

Parameters:

*params: List[str]

names of required parameters

Raises:

tmserver.error.MissingPOSTParameterError

when a required parameter is missing in the request

tmserver.util.assert_query_params(*params)

A decorator for GET request functions that asserts that the query string contains the required parameters.

Parameters:

*params: List[str]

names of required parameters

Raises:

tmserver.error.MissingGETParameterError

when a required parameter is missing in the request

tmserver.util.decode_form_ids(*model_ids)

A decorator that extracts and decodes specified model ids from the POST body and inserts them into the argument list of the view function.

Parameters:

model_ids: *str

encoded model ids

Returns:

The wrapped view function.

Raises:

MalformedRequestError

This exception is raised if an id was missing from the request body.

tmserver.util.decode_query_ids(permission='write')

A decorator that extracts and decodes all model IDs from the URL and inserts them into the argument list of the view function.

Parameters:

permission: str, optional

check whether current user has "read" or "write" permissions for the requested experiment (default: "write")

Returns:

The wrapped view function.

Raises:

MalformedRequestError

when "experiment_id" was missing from the URL

NotAuthorizedError

when requested experiment does not belong to the user

tmserver.util.is_false(value)

Whether a query string parameter should be interpreted as False. False are “False”, “FALSE”, “false”, “no” and 0.

Parameters:value: Union[str, int]
Returns:bool
tmserver.util.is_true(value)

Whether a query string parameter should be interpreted as True. True are “True”, “TRUE”, “true”, “yes” and 1.

Parameters:value: Union[str, int]
Returns:bool

tmserver.version module