90 lines
4.4 KiB
Python
90 lines
4.4 KiB
Python
|
|
from .serializers import FormResponseSerializer
|
|||
|
|
import pandas as pd
|
|||
|
|
from rest_framework import generics, status
|
|||
|
|
from rest_framework.response import Response
|
|||
|
|
from rest_framework.parsers import MultiPartParser, FormParser
|
|||
|
|
from rest_framework.views import APIView
|
|||
|
|
from .models import FormResponse
|
|||
|
|
import logging
|
|||
|
|
from rest_framework.views import APIView
|
|||
|
|
from rest_framework.response import Response
|
|||
|
|
from rest_framework import status
|
|||
|
|
import pandas as pd
|
|||
|
|
from .models import FormResponse # Убедись, что модель импортирована
|
|||
|
|
from .serializers import FormResponseSerializer # Импортируем сериализатор
|
|||
|
|
from django.core.files.storage import default_storage
|
|||
|
|
from django.core.files.base import ContentFile
|
|||
|
|
from datetime import datetime
|
|||
|
|
import json
|
|||
|
|
|
|||
|
|
# API для сохранения ответов
|
|||
|
|
class FormResponseCreateView(generics.CreateAPIView):
|
|||
|
|
queryset = FormResponse.objects.all()
|
|||
|
|
serializer_class = FormResponseSerializer
|
|||
|
|
|
|||
|
|
# API для получения списка ответов
|
|||
|
|
class FormResponseListView(generics.ListAPIView):
|
|||
|
|
queryset = FormResponse.objects.all()
|
|||
|
|
serializer_class = FormResponseSerializer
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
# API для загрузки Excel-файла и сохранения в БД
|
|||
|
|
logger = logging.getLogger(__name__) # Логирование ошибок
|
|||
|
|
|
|||
|
|
|
|||
|
|
class FormResponseUploadView(APIView):
|
|||
|
|
def post(self, request, *args, **kwargs):
|
|||
|
|
print("\n===== [DEBUG] Данные, полученные на сервере =====")
|
|||
|
|
print(json.dumps(request.data, indent=4, ensure_ascii=False)) # Логируем JSON
|
|||
|
|
|
|||
|
|
if "data" not in request.data:
|
|||
|
|
return Response({"error": "Данные не найдены в запросе"}, status=status.HTTP_400_BAD_REQUEST)
|
|||
|
|
|
|||
|
|
uploaded_data = request.data["data"]
|
|||
|
|
responses = []
|
|||
|
|
errors = []
|
|||
|
|
|
|||
|
|
for item in uploaded_data:
|
|||
|
|
# Обработка значений по умолчанию
|
|||
|
|
operators_name = item.get("operators_name", "Анонимный пользователь") or "Анонимный пользователь"
|
|||
|
|
error_zone = item.get("error_zone", "Не указано") or "Не указано"
|
|||
|
|
downtime_reason = item.get("downtime_reason", "Не указано") or "Не указано"
|
|||
|
|
fix_method = item.get("fix_method", "Не указано") or "Не указано"
|
|||
|
|
|
|||
|
|
# Функция для парсинга дат
|
|||
|
|
def parse_date(date_str, default_now=False):
|
|||
|
|
if not date_str:
|
|||
|
|
return datetime.utcnow().isoformat() if default_now else None # Подставляем текущую дату если default_now=True
|
|||
|
|
try:
|
|||
|
|
return datetime.fromisoformat(date_str.replace("Z", "+00:00")).isoformat()
|
|||
|
|
except ValueError:
|
|||
|
|
errors.append({"occurred_at": f"Неверный формат даты: {date_str}"})
|
|||
|
|
return None
|
|||
|
|
|
|||
|
|
occurred_at = parse_date(item.get("occurred_at"), default_now=True) # Если нет даты — ставим текущее время
|
|||
|
|
resolved_at = parse_date(item.get("resolved_at")) # Если нет, оставляем None
|
|||
|
|
|
|||
|
|
response_data = {
|
|||
|
|
"line": item.get("line", "Неизвестная линия"),
|
|||
|
|
"operators_name": operators_name,
|
|||
|
|
"problem": item.get("problem", "Не указано"),
|
|||
|
|
"error_zone": error_zone,
|
|||
|
|
"occurred_at": occurred_at,
|
|||
|
|
"resolved_at": resolved_at,
|
|||
|
|
"downtime_reason": downtime_reason,
|
|||
|
|
"fix_method": fix_method,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
serializer = FormResponseSerializer(data=response_data)
|
|||
|
|
if serializer.is_valid():
|
|||
|
|
responses.append(serializer.save())
|
|||
|
|
else:
|
|||
|
|
errors.append(serializer.errors)
|
|||
|
|
|
|||
|
|
if errors:
|
|||
|
|
print("\n===== [DEBUG] Ошибки при сохранении данных =====")
|
|||
|
|
print(json.dumps(errors, indent=4, ensure_ascii=False)) # Логируем ошибки
|
|||
|
|
return Response({"error": "Некоторые записи не были сохранены", "details": errors}, status=status.HTTP_400_BAD_REQUEST)
|
|||
|
|
|
|||
|
|
return Response({"message": "Данные успешно загружены!", "saved": len(responses)}, status=status.HTTP_201_CREATED)
|