from rest_framework import status, generics from rest_framework.response import Response from rest_framework.views import APIView from django.utils import timezone from .models import Prediction, User, UserPrediction from .serializers import PredictionSerializer from rest_framework.permissions import IsAuthenticated import requests def get_prediction_from_tawhiri(params): base_url = "https://fly.stratonautica.ru/api/v2" response = requests.get(base_url, params=params) if response.status_code == 200: return response.json() # получаем результат предсказания else: raise Exception(f"Tawhiri error: {response.status_code} {response.text}") class PredictionCreateView(APIView): def post(self, request): user_id = request.data.get('user_id') user = User.objects.get(id=user_id) # Передаём остальные параметры (кроме user_id) в Tawhiri tawhiri_params = {k: v for k, v in request.data.items() if k != 'user_id'} try: prediction_result = get_prediction_from_tawhiri(tawhiri_params) except Exception as e: return Response({"error": str(e)}, status=500) prediction = Prediction.objects.create(result=prediction_result) UserPrediction.objects.create(user=user, prediction=prediction) return Response(PredictionSerializer(prediction).data) class PredictionListView(APIView): def get(self, request): user_id = request.query_params.get('user_id') created_from = request.query_params.get('created_from') created_till = request.query_params.get('created_till') predictions = Prediction.objects.filter( id__in=UserPrediction.objects.filter(user_id=user_id).values_list('prediction_id'), created_at__gte=created_from, created_at__lte=created_till, deleted_at__isnull=True ) return Response(PredictionSerializer(predictions, many=True).data) class PredictionDeleteView(APIView): def delete(self, request, pk): try: prediction = Prediction.objects.get(pk=pk) prediction.deleted_at = timezone.now() prediction.save() return Response({"deleted": True}) except Prediction.DoesNotExist: return Response({"error": "Not found"}, status=404) class PredictionCreateView(APIView): permission_classes = [IsAuthenticated]