ft_transcendence/tournament/viewset.py

59 lines
2.1 KiB
Python
Raw Normal View History

from rest_framework import viewsets
2023-12-20 13:15:47 -05:00
from rest_framework.response import Response
from rest_framework import permissions, status
from rest_framework.authentication import SessionAuthentication
from django.http import HttpRequest
from django.contrib.auth import login
from django.db.models import QuerySet
2023-12-20 13:15:47 -05:00
from matchmaking.models import in_matchmaking
from .models import TournamentModel
from .serializers import TournamentSerializer
2023-12-20 13:15:47 -05:00
# Create your views here.
class TournamentViewSet(viewsets.ModelViewSet):
2023-12-20 13:15:47 -05:00
queryset = TournamentModel.objects.all
serializer_class = TournamentSerializer
2023-12-20 13:15:47 -05:00
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def perform_create(self, request: HttpRequest):
2023-12-20 13:15:47 -05:00
data: dict = request.data
nb_players_by_game = data.get("nb_players_by_game")
if (nb_players_by_game is None):
return Response("nb_player_by_game is required.", status=status.HTTP_400_BAD_REQUEST)
nb_players = data.get("nb_players")
if (nb_players is None):
return Response("nb_players is required.", status=status.HTTP_400_BAD_REQUEST)
tournament_id: int = TournamentModel().create(nb_players=nb_players, nb_players_by_game=nb_players_by_game)
2023-12-20 13:15:47 -05:00
return Response({"tournament_id": tournament_id}, status=status.HTTP_201_CREATED)
def list(self, request: HttpRequest, state: str = ""):
query: QuerySet
match state:
case "started":
query = TournamentModel.objects.filter(started=True, finished=False)
case "finished":
query = TournamentModel.objects.filter(finished=True)
case "currently":
query = TournamentModel.objects.filter(started=False, finished=False)
case _:
query = TournamentModel.objects.all()
serializer = TournamentSerializer(query, many=True)
return Response(serializer.data)
def retrieve(self, request: HttpRequest, pk):
2023-12-20 13:15:47 -05:00
if (not TournamentModel.objects.filter(pk=pk).exists()):
return Response({"detail": "Tournament not found."}, status=status.HTTP_404_NOT_FOUND)
tournament = TournamentModel.objects.get(pk=pk)
return Response(self.serializer_class(tournament).data, status=status.HTTP_200_OK)