Skip to content
blocks.py 1.84 KiB
Newer Older
vertighel's avatar
vertighel committed
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''REST API to edit Observation Blocks'''

from flask_restx import Namespace, Resource
vertighel's avatar
vertighel committed

# Custom modules
from utils.data_access_object import ObservationBlockObject as DAO
from utils.data_access_object import guess
vertighel's avatar
vertighel committed

dao = DAO("ob")
tpl = DAO("defaults")
Davide Ricci's avatar
Davide Ricci committed

api = Namespace('blocks', description='Observation blocks')
vertighel's avatar
vertighel committed

@api.route("/")
class BlockList(Resource):
    """Show and create OBs"""
vertighel's avatar
vertighel committed

vertighel's avatar
vertighel committed
    def get(self):
        """Show all observation OB files"""
        return dao.todos

    def post(self):
        """Create a new OB file based on name"""
        name = api.payload
        dao.create(name)
        return "", 204

    def delete(self):
        """Delete an OB file based on name"""
        name = api.payload
        dao.delete(name)
        return "", 204

@api.route("/<string:name>")
@api.param("name", "The uniqe name of the OB")
class Block(Resource):
    """Show a selected OB, update it, or add a new
    template in it.
    """

    def get(self, name):
        """Show a specific OB"""
        return dao.show(name)

    def put(self, name):
        """Update the OB"""
        data = api.payload
Davide Ricci's avatar
Davide Ricci committed
        for datum in data:
            for key, val in datum["params"].items():
                datum["params"][key] = guess(val)
vertighel's avatar
vertighel committed
        dao.update(name, data)
        return "", 204

    def post(self, name):
        """Add a template to the selected OB"""
        content = dao.content(name)
        new_data = tpl.content(api.payload)
        data = content + new_data
vertighel's avatar
vertighel committed
        dao.update(name, data)
        return "", 204

    def delete(self, name):
        """Delete a template instance in the selected OB"""
        instance = api.payload
        data = dao.content(name)
        data.pop(instance - 1) # jinjia loop starts from 1 in html
vertighel's avatar
vertighel committed
        dao.update(name, data)
        return "", 204