Skip to content
Snippets Groups Projects
folder.py 1.31 KiB
import logging
from requests.exceptions import HTTPError
from brian_dashboard_manager.grafana.utils.request import TokenRequest


logger = logging.getLogger(__name__)


def delete_folder(request: TokenRequest, title=None, uid=None):
    if uid:
        r = request.delete(f'api/folders/{uid}')
        return r is not None
    else:
        folder = find_folder(request, title, False)
        if folder is None:
            return True
        r = request.delete(f'api/folders/{folder.get("uid")}')
        logger.info(f'Deleted folder: {title}')
        return r is not None


def find_folder(request: TokenRequest, title, create=True):
    folders = get_folders(request)
    try:
        folder = next(
            f for f in folders if f['title'].lower() == title.lower())
    except StopIteration:
        folder = None

    if not folder and create:
        logger.info(f'Created folder: {title}')
        folder = create_folder(request, title)
    return folder


def get_folders(request: TokenRequest):
    return request.get('api/folders')


def create_folder(request: TokenRequest, title):
    try:
        data = {'title': title, 'uid': title.replace(' ', '_')}
        r = request.post('api/folders', json=data)
    except HTTPError:
        logger.exception(f'Error when creating folder {title}')
        return None
    return r