API Definition

App Kernel Engine

The main application class, which exposes the Service classes, manages Repositories and applies security.

class appkernel.AppKernelEngine(app_id: str, app: flask.app.Flask = None, root_url: str = '/', log_level=10, cfg_dir: str = None, development: bool = False, enable_defaults: bool = True)
generic_error_handler(ex: Exception = None, upstream_service: str = None)

Takes a generic exception and returns a json error message which will be returned to the client :param ex: the exception which is reported by this method :param upstream_service: the servicr name which generated this error :return:

register(service_class_or_instance, url_base=None, methods=['GET'], enable_hateoas=True) → appkernel.engine.ResourceController
Parameters:
  • service_class_or_instance
  • url_base
  • methods
  • enable_hateoas
Returns:

Return type:

Service

teardown(exception)

context teardown based deallocation :param exception: :type exception: Exception :return:

Model

The base class to be extended by all Domain objects (Models). It has a set of useful methods, such as JSON marshaling, metadata (json schema) generation and validation. Example:

class User(Model):
        id = Property(str)
        name = Property(str, required=True, index=UniqueIndex)
        email = Property(str, validators=Email, index=UniqueIndex)
        password = Property(str, validators=NotEmpty,
                             converter=content_hasher(), omit=True)
class appkernel.Model(**kwargs)

The base class of all Model objects which are intended to be persisted in the database or served via REST;

append_to(**kwargs)

Appends one or more objects to a list (eg. User(name=’user name’).append(roles=[‘Admin’]).

Parameters:kwargs (objects) – named arguments, representing a list object
Returns:the current object itself.
Return type:Model
classmethod custom_property(custom_field_name)

It is used to be search for property names which are not defined explicitly on the class. Sample: project = Project.find_one(Project.custom_property(‘version’) == 2)

Parameters:custom_field_name (str) – the name of the property
dump_spec()

Prints the parameter specification of the model

dumps(validate: bool = True, pretty_print: bool = False, json_serialiser_func: Callable = None) → str

Returns the json representation of the object.

Parameters:
  • validate (bool) – if True (default), will validate the object before converting it to Json;
  • pretty_print (bool) – if True (False by default) it will format the json object upon conversion;
  • json_serialiser_func (Callable) – a custom function which can be used to serialise variables
Returns:

the json object as a string

Return type:

str

finalise_and_validate()

Calls the generator, default value calculator and converter methods first, than it validates the object;

Raises:
  • ParameterRequiredException – in case some value property is mandatory
  • ValidationException – in case one of the parameter validators do not validate
static from_dict(dict_obj: dict, cls, convert_ids=False, set_unmanaged_parameters=True, converter_func=None)

Reads a dictionary representation of the model and turns it into a python object model.

Parameters:
  • set_unmanaged_parameters (bool) – if False, key-value pairs from the dict object which are not class variables on the Model (there is no Parameter object for them) will not be set
  • convert_ids (bool) – strip the underscore prefix from object id parameter is exists ( _id -> id )
  • dict_obj (dict) – the dictionary to be converted to object
  • cls (type) – the type of the object needs to be returned
  • converter_func – used to convert some of the object types (such as mongo converter)
Returns:

an instantiated object from the dict

Return type:

Model

static from_list(list_obj, item_cls, convert_ids=False, converter_func=None)

Converts a list of dict structures to a list of Model instances. It is mainly used from the Model.from_dict method.

Parameters:
  • list_obj (list) – a list of dict objects representing a model;
  • item_cls (type) – the class of the Model to which the dict is loaded
  • convert_ids (bool) – if true, it will convert ids with underscore prefix (from ‘_id’ to ‘id’)
Returns:

the list of Model objects

Return type:

list

classmethod get_json_schema(additional_properties: bool = True, mongo_compatibility: bool = False) → dict

Generates a JSON Schema document from the Model.

Parameters:
  • additional_properties (bool) – if True the schema will have an additional parameter called ‘additionalProperties’:true (this will allow to have extra elements in the json schema)
  • mongo_compatibility (bool) – if true, the generated json schema will be compatible with mongo
Returns:

the schema of the current object as a dictionary object

Return type:

dict

classmethod get_paramater_spec_as_json()

Describes the parameters found on the Model implementation, including details, such as type, validators, etc.

Returns:json parameter specification description
Return type:str
classmethod get_parameter_spec(convert_types_to_string=True)

Describes the parameters found on the Model implementation, including details, such as type, validators, etc.

Parameters:convert_types_to_string (bool) – when true (default behaviour) the definition will contain the string representation of the python types;
Returns:a dict object, defining all parameters found on the Model instance;
Return type:dict
classmethod loads(json_string) → appkernel.model.Model

Takes a json string and creates a python object from it.

Parameters:json_string (str) – the Json string to be converted into an object
Returns:the generated object (it won’t run validation on it)
Return type:Model
remove_from(**kwargs)

Deletes one or more elements from a parameter of list type (eg. roles=’Admin’).

Parameters:kwargs (object) – the name of the list parameter and the value;
Raises:AttributeError – when the named attribute cannot be found on the object.
Returns:the self object for chaining further method calls
Return type:Model
static to_dict(instance, convert_id=False, validate=True, skip_omitted_fields=False, marshal_values=True, converter_func=None) → dict

Turns the python instance object into a dictionary after finalising and validating it.

Parameters:
  • skip_omitted_fields (bool) – if True, the fields marked with ommitted=True will be excluded from the result;
  • validate (bool) – if False (default: True), the validation of the object will be skipped
  • convert_id (bool) – it will convert id fields to _id representation for fitting Mongodb’s requirements
  • instance (Model) – the python instance object
  • skip_omitted_fields – False by default. Used to avoid sending over specific values through the wire;
  • marshal_values (bool) – use the Marshallers to convert some values specific to the wireformat;
  • converter_func (Callable) – a function which will take one instance variable as input and return a possibly converted one;
Returns:

a dictionary representing the python Model object

Return type:

dict

update(**kwargs)

Updates an existing attribute. The only difference compared to standard attribute value assignment is that it accepts multiple assignments in one line and returns the object instance, enabling further method calls;

Parameters:kwargs (object) – key value pairs which will be set on the instance
Returns:the Model instance
Return type:Model

Property

class appkernel.Property(python_type, required: bool = False, sub_type: Callable = None, validators: Callable = None, converter: Callable = None, default_value: Callable = None, generator: Callable = None, index: appkernel.model.Index = None, marshaller: Callable = None, omit=False)

Metadata holder used by the Model classes.

__init__(python_type, required: bool = False, sub_type: Callable = None, validators: Callable = None, converter: Callable = None, default_value: Callable = None, generator: Callable = None, index: appkernel.model.Index = None, marshaller: Callable = None, omit=False) -> ()
Parameters:
  • python_type (type) – the primary python type of the attribute (eg. str, datetime or anything else);
  • required (bool) – if True, the field must be specified before validation;
  • sub_type (type) – in case the python type is a dict or a list (or any other collection type), one needs to specify the element types
  • validators (Validator) – a list of validator elements which are used to validate field content
  • converter – converts the value of the property in the finalisation phase (before generating a json or saving in the database). Useful to hash passwords or encrypt custom content;
  • default_value (object) – this value is set on the field in case there’s no other value there yet
  • generator (function) – content generator, perfect for date.now() generation or for field values calculated from other fields (eg. signatures)
  • index (Index) – the type of index (if any) which needs to be added to the database;
  • marshaller (Marshaller) –
  • omit (bool) – if True, the field won’t be included in the json or other wire-format messages
asc()

Adds ASCENDING sorting order to the query.

Returns:reference to self
Return type:Model
desc()

Adds DESCENDING sorting order to the query.

Returns:reference to self
Return type:Model

Validators

The base Validator class

class appkernel.Validator(validator_type, value=None, message=None)

a root object for different type of validators

__init__(validator_type, value=None, message=None)

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name: str, validable_object: any)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Not Empty Validator

class appkernel.NotEmpty

Used for string types to make sure that there’s a string with length longer than 0. Also checks lists for a size.

__init__()

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Regular Expression Validator

class appkernel.Regexp(value)
__init__(value)

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Email Validator

class appkernel.Email

It is a convenience validator extending the Regexp validator and initialising it with an e-mail regular expression.

__init__()

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Minimum Validator

class appkernel.Min(minimum)
__init__(minimum)

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Maximum Validator

class appkernel.Max(maximum)
__init__(maximum)

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Past Validator

class appkernel.Past
__init__()

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Future Validator

class appkernel.Future
__init__()

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Unique Value Validator

class appkernel.Unique
__init__()

Initialize self. See help(type(self)) for accurate signature.

validate(parameter_name, validable_object)

Validates and object against the validation parameters.

Parameters:
  • parameter_name
  • validable_object
Raises:

ValidationException

Generators

UUID Generator

appkernel.create_uuid_generator(prefix=None)

Date NOW Generator

appkernel.date_now_generator()

Password hasher

appkernel.content_hasher(rounds=20000, salt_size=16)

Repository

The current implementation is the MongoRepository.

class appkernel.Repository
__init__

Initialize self. See help(type(self)) for accurate signature.

classmethod count(query_filter={})

Return the number of items matching the query filter :param query_filter: the raw query type as a dict (using the mongo syntax) :type query_filter: dict :return:

classmethod create_object(document)

Insert a new object in the database :param document: :return:

delete()

Delete the current instance. :raises RepositoryException: in case the instance was not deleted.

classmethod delete_all()
Returns:
classmethod delete_by_id(object_id)

Delete the object identified by ID :param object_id: the unique object ID :return:

classmethod delete_many(match_query_dict)
Parameters:match_query_dict
Returns:
classmethod find(*expressions)
Parameters:expressions (Expression) –
Returns:a Model Generator
classmethod find_by_id(object_id)

Find an object identified by the unique database id :param object_id: the database id :return:

classmethod find_by_query(query={}, page=1, page_size=50, sort_by=None, sort_order=<SortOrder.ASC: 1>)
Parameters:
  • query (dict) –
  • page (int) –
  • page_size (int) –
  • sort_by
  • sort_order
Returns:

classmethod find_one(*expressions)

Returns one single instance of the Model. :param expressions: :type expressions: Expression :return: one Model object :rtype: Model

classmethod replace_object(object_id, document)

Replace the object in the database. :param object_id: :param document: :return:

save()

Saves or updates a model instance in the database :return: the id of the inserted or updated document

classmethod update_many(match_query_dict, update_expression_dict)
Parameters:
  • match_query_dict
  • update_expression_dict
Returns:

classmethod where(*expressions)

Creates and returns a query object, used for further chaining functions like sorting and pagination; :param expressions: the query filter expressions used to narrow the result-set :return: a query object preconfigured with the :rtype: Query

Query

class appkernel.Query(*expressions)

a class representing the query

__init__(*expressions)

Initialize self. See help(type(self)) for accurate signature.

count()
Returns:the number of items in the repository matching the filter expression;
delete()

Delete all elements which fulfill the filter criteria (defined in the where method); :return: the deleted item count

find()

Creates a cursor based on the filter and sorting criteria and yields the results; :return: a generator object which yields found instances of Model class

find_one()
Returns:One or none instances of the Model, depending on the query criteria
get(page=0, page_size=100)

Returns the list of found Model instances; :param page: the current page requested :param page_size: the size of the page (number of elements requested :return: the result of the query as a list of Model instance objects

sort_by(*sorting_tuples)

Defines sorting criteria (eg. .sort_by(User.name.desc()) :param sorting_tuples: desc() or asc() on the Model parameter :return: self for calling further methods on the class :rtype: Query

MongoRepository

class appkernel.MongoRepository
classmethod add_schema_validation(validation_action='warn')
Parameters:validation_action – warn or error (MongoDB logs any violations but allows the insertion or update to proceed)
Returns:
classmethod count(query_filter={})

Return the number of items matching the query filter :param query_filter: the raw query type as a dict (using the mongo syntax) :type query_filter: dict :return:

static create_index(collection, field_name, sort_order, unique=False)
Parameters:
  • collection (pymongo.collection.Collection) – the collection to which the index is applied to
  • field_name (str) – the name of the document field which is being indexed
  • sort_order (SortOrder) – the sort order
  • unique (bool) – if true (false by default) it will create a unique index
classmethod create_object(document)

Insert a new object in the database :param document: :return:

delete()

Delete the current instance. :raises RepositoryException: in case the instance was not deleted.

classmethod delete_all()

deletes all documents from the collection :return: the count of deleted documents

classmethod delete_by_id(object_id)

Deletes a document identified by the object id :param object_id: :return: true if the object was deleted

classmethod delete_many(match_query_dict)
Parameters:match_query_dict
Returns:
classmethod find(*expressions)
Parameters:expressions (Expression) –
Returns:a Model Generator
classmethod find_by_id(object_id)

Find an object identified by the unique database id :param object_id: the database id :return:

classmethod find_by_query(query={}, page=1, page_size=50, sort_by=None, sort_order=<SortOrder.ASC: 1>)

query using mongo’s built-in query language :param sort_order: :param sort_by: :param page_size: :param page: :param query: the query expression as a dictionary :return: a generator with the query results

classmethod find_one(*expressions)

Returns one single instance of the Model. :param expressions: :type expressions: Expression :return: one Model object :rtype: Model

classmethod get_collection() → pymongo.collection.Collection
Returns:the collection for this model object
Return type:Collection
classmethod replace_object(model: appkernel.model.Model)

Replace the object in the database. :param object_id: :param document: :return:

save()

Saves or updates a model instance in the database :return: the id of the inserted or updated document

classmethod update_many(match_query_dict, update_expression_dict)

updates multiple documents in the database :param match_query_dict: the query expression to match the documents to be updated :param update_expression_dict: :return: the number of modified documents

classmethod where(*expressions) → appkernel.repository.MongoQuery

Creates and returns a query object, used for further chaining functions like sorting and pagination; :param expressions: the query filter expressions used to narrow the result-set :return: a query object precofigured with the :rtype: MongoQuery

Auditable Repository

class appkernel.AuditableRepository(**kwargs)
save()

Saves or updates a model instance in the database :return: the id of the inserted or updated document

MongoQuery

class appkernel.MongoQuery(connection_object: pymongo.collection.Collection, user_class, *expressions)
__init__(connection_object: pymongo.collection.Collection, user_class, *expressions)

Initialize self. See help(type(self)) for accurate signature.

count() → int
Returns:the number of items in the repository matching the filter expression;
delete() → int
Returns:the delete count
find(page: int = 0, page_size: int = 100) → appkernel.model.Model

Returns a generator for the number of pages :param page: current page :param page_size: number of elements :return: a generator which can be used in an iteration

find_one()
Returns:one instance of the Model or None
Return type:Model
get(page: int = 0, page_size: int = 100) → list

Return the complete list of all items corresponding to the query :param page: current page :param page_size: the number of elements :return: a list of all items corresponding the query

Service