api.py 1.64 KB
import json
from rest_framework import viewsets,mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework import status
from rest_framework.response import Response
from rest_framework_api_key.permissions import HasAPIKey

from datetime import datetime

from .models import Evento
from .serializers import EventoSerializer
from .service import GenerarFechas


class EventoViewSets(
    mixins.CreateModelMixin,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    viewsets.GenericViewSet,
):
    queryset = Evento.objects.all().order_by('id')
    serializer_class = EventoSerializer
    permission_classes = [HasAPIKey | IsAuthenticated]
    lookup_field = 'id'

    @action(methods=['POST'], detail=False, url_path='obtener-mes')
    def obtener_mes(self, request):
        mes_query = request.data.get('mes', None)

        if mes_query is None:
            return Response(
                data={
                    'error':
                        'El mes ingresado no es válido. '
                        'Por favor, ingrese el mes correspondiente a la fecha actual o posterior.'
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        eventos = Evento.objects.filter(fecha_inicio__month=mes_query)
        evento_json = []
        for evento in eventos:
            generar_fechas = GenerarFechas(evento=evento, mes=mes_query)
            generar_fechas.procesar_fechas_evento()  # Cambiado a 'procesar_fechas_evento()'
            evento_json.append(generar_fechas.obtener_datos_evento())

        return Response(data=evento_json, status=status.HTTP_200_OK)