Marble/server/metric/views.py

49 lines
1.8 KiB
Python
Raw Permalink Normal View History

2024-10-05 19:53:31 +04:00
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from .models import Metric
2024-10-09 21:15:08 +04:00
from .serializers import MetricSerializer, MetricListSerializer
2024-10-05 19:53:31 +04:00
@api_view(['GET', 'POST'])
def metric_list(request):
2024-10-09 21:15:08 +04:00
user = request.user
2024-10-05 19:53:31 +04:00
if request.method == 'GET':
metrics = Metric.objects.all()
2024-10-09 21:15:08 +04:00
serializer = MetricListSerializer(metrics, many=True)
2024-10-05 19:53:31 +04:00
return Response(serializer.data)
2024-10-09 21:15:08 +04:00
elif request.method == 'POST':
if Metric.objects.filter(user=user).exists():
return Response({'detail': 'Metric already exists for this user.'}, status=status.HTTP_400_BAD_REQUEST)
serializer = MetricSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2024-10-05 19:53:31 +04:00
2024-10-09 21:15:08 +04:00
@api_view(['GET', 'PUT', 'DELETE'])
2024-10-05 19:53:31 +04:00
def metric_detail(request):
user = request.user
if request.method == 'GET':
metric = get_object_or_404(Metric, user=user)
serializer = MetricSerializer(metric)
return Response(serializer.data)
elif request.method == 'PUT':
metric = get_object_or_404(Metric, user=user)
serializer = MetricSerializer(metric, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
metric = get_object_or_404(Metric, user=user)
metric.delete()
return Response({'detail': 'Metric deleted successfully.'}, status=status.HTTP_204_NO_CONTENT)