from flask import Blueprint from flask_apispec import use_kwargs, marshal_with from flask_jwt_extended import jwt_required from marshmallow import fields from api.exceptions import NotFoundException, BadRequestException from api.target_exchange.models import TargetExchange from api.utils import docwrap from .models import Target from .serializers import target_schema, targets_schema blueprint = Blueprint('target', __name__) doc = docwrap('Target') @doc @blueprint.route('', methods=['GET']) @jwt_required() @use_kwargs({'exchange': fields.Str()}, location='query') @marshal_with(targets_schema) def get_list(exchange=None): res = Target.query if exchange is not None: res = res.join(Target.exchange).filter(TargetExchange.name == exchange) return res.all() @doc @blueprint.route('', methods=['POST']) @jwt_required() @use_kwargs(target_schema) @marshal_with(target_schema) def create(name, routing_key, exchange): xchange = TargetExchange.get_by_id(exchange.id) if xchange is None: raise BadRequestException(f"the exchange {exchange.name}({exchange.id}) could not be found") target = Target(name=name, routing_key=routing_key, target_exchange_id=xchange.id) target.save() return target @doc @blueprint.route('/', methods=['GET']) @jwt_required() @marshal_with(target_schema) def get_by_id(target_id: int): target_exchange = Target.get_by_id(target_id) if target_exchange is not None: return target_exchange else: return NotFoundException(Target.__name__) @doc @blueprint.route('/', methods=['PUT']) @jwt_required() @use_kwargs(target_schema) @marshal_with(target_schema) def update(target_id, **kwargs): target_exchange = Target.get_by_id(target_id) if target_exchange is not None: return target_exchange.update(**kwargs) else: return NotFoundException(Target.__name__)