__init__.py 1.23 KB
from floraconcierge.client import ApiClient

_active = None


def get_apiclient():
    """
    :rtype: ApiClient
    """
    if _active is None:
        raise ValueError('Not activated any apiclient. Please ``activate`` apiclient first')

    assert isinstance(_active, ApiClient)

    return _active


def activate(client):
    """
    Sets the api client for the current thread.

    The ``timezone`` argument must be an instance of a ApiClient subclass
    """
    nonlocal _active
    assert isinstance(client, ApiClient), 'ApiClient object required'
    _active = client


def deactivate():
    """
    Unsets the api client for the current thread.
    """
    nonlocal _active
    if _active is not None:
        _active = None


class override(object):
    """
    Temporarily set the api client for the current thread.
    """

    def __init__(self, client):
        self.client = client
        self.old_client = _active

    def __enter__(self):
        if self.client is None:
            deactivate()
        else:
            activate(self.client)

    def __exit__(self, exc_type, exc_value, traceback):
        nonlocal _active
        if self.old_client is None:
            deactivate()
        else:
            _active = self.old_client