Skip to content
Snippets Groups Projects
funding.py 2.14 KiB
import logging

from flask import Blueprint, jsonify, current_app

from compendium_v2 import db
from compendium_v2.routes import common
from compendium_v2.db import model
from typing import Any

routes = Blueprint('funding', __name__)


@routes.before_request
def before_request():
    config = current_app.config['CONFIG_PARAMS']
    dsn_prn = config['SQLALCHEMY_DATABASE_URI']
    db.init_db_model(dsn_prn)


logger = logging.getLogger(__name__)

FUNDING_RESPONSE_SCHEMA = {
    '$schema': 'http://json-schema.org/draft-07/schema#',

    'definitions': {
        'funding': {
            'type': 'object',
            'properties': {
                'id': {'type': 'number'},
                'NREN': {'type': 'string'},
                'YEAR': {'type': 'integer'},
                'CLIENT_INSTITUTIONS': {'type': 'number'},
                'EUROPEAN_FUNDING': {'type': 'number'},
                'GOV_PUBLIC_BODIES': {'type': 'number'},
                'COMMERCIAL': {'type': 'number'},
                'OTHER': {'type': 'number'}
            },
            'required': ['NREN', 'YEAR'],
            'additionalProperties': False
        }
    },

    'type': 'array',
    'items': {'$ref': '#/definitions/funding'}
}


@routes.route('/', methods=['GET'])
@common.require_accepts_json
def funding_source_view() -> Any:
    """
    handler for /api/funding/ requests

    response will be formatted as:

    .. asjson::
        compendium_v2.routes.funding.FUNDING_RESPONSE_SCHEMA

    :return:
    """

    def _extract_data(entry: model.FundingSource):
        return {
            'NREN': entry.nren.name,
            'YEAR': entry.year,
            'CLIENT_INSTITUTIONS': float(entry.client_institutions),
            'EUROPEAN_FUNDING': float(entry.european_funding),
            'GOV_PUBLIC_BODIES': float(entry.gov_public_bodies),
            'COMMERCIAL': float(entry.commercial),
            'OTHER': float(entry.other)
        }

    with db.session_scope() as session:
        entries = sorted([_extract_data(entry)
                         for entry in session.query(model.FundingSource)],
                         key=lambda d: (d['NREN'], d['YEAR']))
    return jsonify(entries)