Skip to content
Snippets Groups Projects
mic.py 1.71 KiB
"""
Maintenance Impact Calculator support Endpoints
=================================================

These endpoints are intended for use by the Maintenance Impact Calculator tool

.. contents:: :local:

/mic/sites
----------------------

.. autofunction:: inventory_provider.routes.mic.sites


"""
import json
import logging

from flask import Blueprint, request, current_app, Response

from inventory_provider.routes import common
from inventory_provider.routes.common import _ignore_cache_or_retrieve

logger = logging.getLogger(__name__)
routes = Blueprint('mic-support-routes', __name__)

SITES_LIST_SCHEMA = {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "abbreviation": {"type": "string"}
        },
        "required": ["name", "abbreviation"],
        "additionalProperties": False
    }
}


@routes.route('/sites')
def get_sites():
    cache_key = 'classifier-cache:mic:sites'
    r = common.get_current_redis()
    result = _ignore_cache_or_retrieve(request, cache_key, r)
    if not result:
        def _fetch_sites():
            config = current_app.config['INVENTORY_PROVIDER_CONFIG']
            for doc in common.load_json_docs(
                config_params=config,
                key_pattern='ims:pop:*'
            ):
                yield {
                    'name': doc['value']['name'],
                    'abbreviation': doc['value']['abbreviation'],
                }
        sites = sorted(_fetch_sites(), key=lambda x: x['name'])
        result = json.dumps(sites)
        r.set(cache_key, result.encode('utf-8'))

    return Response(result, mimetype='application/json')