#!/usr/bin/env python3 from app import rabbitmq_channel import logging import json import rstr from flask_restful import Resource, reqparse from werkzeug.datastructures import FileStorage import requests import filetype import db from models import SampleMetadata from schemas import * from config import * """ Flask Restful endpoints """ __author__ = '@tormakris' __copyright__ = "Copyright 2020, Birbnetes Team" __module_name__ = "endpoints" __version__text__ = "1" LOGGER = logging.getLogger(__name__) class SampleResource(Resource): """ Sample endpoint See: https://swagger.kmlabz.com/?urls.primaryName=Input%20Service """ def post(self): """ Post request send to the endpoint :return: """ parse = reqparse.RequestParser() parse.add_argument('soundFile', type=FileStorage, location='soundFile') parse.add_argument('description', type=str, location='description') args = parse.parse_args() soundFile = args['soundFile'] description = args['description'] kind = filetype.guess(soundFile) if kind.mime != 'wav': LOGGER.error( "Input file was not WAV. Recieved metadata: {}", description) return {'status': 'error', 'message': 'Input file not WAV.'}, 415 try: desc = json.loads(description) except Exception as e: LOGGER.exception(e) return {'status': 'error', 'message': 'Input JSON could not be parsed'}, 400 validate_errors = SampleSchema().validate(desc) if validate_errors: LOGGER.error( "Input JSON did not conform to schema. It was: {}", desc) return {'status': 'error', 'message': 'Input JSON schema invalid'}, 417 generated_tag = rstr.xeger(r'^[a-zA-Z]+[0-9a-zA-Z_]*$', 2, 32) record = SampleMetadata( device_id=desc['device_id'], device_date=desc['date'], tag=generated_tag) try: db.session.add(record) requests.post( f"http://{STORAGE_HOSTNAME}/object", files={ 'tag': (None, generated_tag), 'file': ( 'wave.wav', soundFile, kind.mime)}) rabbitmq_channel.basic_publish( exchange=RABBITMQ_EXCHANGE, routing_key='feature', body=generated_tag) except Exception as e: LOGGER.exception(e) db.session.rollback() return {"status": "exception", "message": str( e), "hint": "DB or downstream service error"}, 569 db.session.commit() return {"status": "ok", "message": generated_tag}, 200