Source code for sqlbatis.container
from .errors import ContainerException
from werkzeug.local import Local
[docs]def entity(cls):
"""Hand over the instance management to the container
:return: cls object
:rtype: SQLBatisMetaClass class
"""
SQLBatisContainer.register(cls.__name__, None)
return cls
[docs]class SQLBatisContainer:
"""The container for the SQLBatis injection, it will hold the instance
that class which inherit the SQLBatisMetaClass
:raises ContainerException: will raise exception if no instance is registered
"""
__local__ = Local()
[docs] @staticmethod
def register(key, instance):
"""Register the instance to the container
:param key: the key of the instance
:type key: str
:param instance: the instance of the cls
:type instance: cls instance
"""
setattr(SQLBatisContainer.__local__, key, instance)
[docs] @staticmethod
def get(key):
"""Try to get the instance from the container
:param key: the key of the instance
:type key: str
:raises ContainerException: if no instance is binded with the key, will raise the exception
:return: the instance
:rtype: cls instance
"""
try:
instance = getattr(SQLBatisContainer.__local__, key)
if not instance:
raise ContainerException(
'There is no object bounded with the key {}'.format(key))
return instance
except Exception:
raise ContainerException('No {} instance registered'.format(key))
[docs] @staticmethod
def has_key(key):
"""Check if the instance exist in the container
:param key: the instance key
:type key: str
:return: True if the instance exists else False
:rtype: bool
"""
return hasattr(SQLBatisContainer.__local__, key)