Merge pull request 'API for events data' (#33) from Danhia/website:api-events into main

Reviewed-on: 42CTF/website#33
This commit is contained in:
Danhia 2022-03-19 20:42:35 +01:00
commit 7dad96d79f
2 changed files with 31 additions and 1 deletions

View File

@ -3,4 +3,5 @@ from . import views
urlpatterns = [
path('bot/discord', views.discord_bot, name='discord_bot'),
path('events/<str:event_slug>', views.events_data, name='events_data'),
]

View File

@ -2,6 +2,8 @@ from django.shortcuts import render
from accounts.models import UserProfileInfo
from django.http import JsonResponse
import os
from events.models import Event, Team, EventPlayer
from django.shortcuts import get_object_or_404
# Create your views here.
@ -25,3 +27,30 @@ def discord_bot(request):
rank += 1
return JsonResponse(data)
def events_data(request, event_slug):
if request.method != 'GET':
return JsonResponse({'error':'bad request'})
event_info = get_object_or_404(Event, slug=event_slug)
if event_info.password and request.GET.get('password') != event_info.password:
return JsonResponse({'error':'not authorized'})
players = EventPlayer.objects.filter(event=event_info)
data = {}
if event_info.team_size > 1:
for player in players:
if not player.team:
continue
if not player.team.name in data:
data[player.team.name] = []
data[player.team.name].append({"name": player.user.username, "score": player.score})
else:
for player in players:
data[player.user.username] = player.score
return JsonResponse(data)