From 17f9eec1dce4b2dca584b1c4c6e7b0d51a074eb0 Mon Sep 17 00:00:00 2001 From: Matthew Richards Date: Thu, 22 Oct 2020 19:04:54 +0000 Subject: [PATCH] #154: Add function to get instance of DB model entity from a name --- common/database/models.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/common/database/models.py b/common/database/models.py index aa0303ef..7e8790ac 100644 --- a/common/database/models.py +++ b/common/database/models.py @@ -20,7 +20,7 @@ from sqlalchemy.orm import relationship from sqlalchemy.orm.collections import InstrumentedList -from common.exceptions import FilterError, DatabaseError +from common.exceptions import FilterError, DatabaseError, ApiError Base = declarative_base() @@ -58,6 +58,25 @@ class EntityHelper(object): EntityHelper class that contains methods to be shared across all entities """ + @staticmethod + def get_entity_object_from_name(entity_name): + """ + From an entity name, this function gets a Python version of that entity for the + database backend + + :param entity_name: Name of the entity to fetch a version from this model + :type entity_name: :class:`str` + :return: Object of the entity requested (e.g. + :class:`common.database.models.INVESTIGATIONINSTRUMENT`) + :raises: KeyError: If an entity model cannot be found as a class in this model + """ + try: + return globals()[entity_name.upper()] + except KeyError: + raise ApiError( + f"Entity class cannot be found. Please create a class for {entity_name}" + ) + def to_dict(self): """ Turns the columns and values of an entity into a dictionary