|
1 | 1 | from django.shortcuts import get_object_or_404 |
2 | 2 | from django.utils.decorators import method_decorator |
| 3 | +from django.conf import settings |
3 | 4 |
|
4 | 5 | from rest_framework.response import Response |
5 | 6 | from rest_framework.views import APIView |
6 | 7 | from rest_framework import status |
7 | 8 |
|
| 9 | +import requests |
| 10 | +import secrets |
| 11 | + |
8 | 12 | from segmentoj.decorator import parameter_required, syllable_required |
9 | 13 | from status.models import Status |
10 | 14 | from problem.models import Problem |
@@ -44,3 +48,36 @@ def get(self, request, pid): |
44 | 48 | ps = ProblemSerializer(problem) |
45 | 49 | return Response({'res': ps.data}, status=status.HTTP_200_OK) |
46 | 50 |
|
| 51 | +class JudgerTokenView(APIView): |
| 52 | + @method_decorator(judger_account_required()) |
| 53 | + def get(self, request): |
| 54 | + token = secrets.token_urlsafe(64) |
| 55 | + |
| 56 | + try: |
| 57 | + res = requests.post('{base_url}/api/token'.format(base_url=settings.JUDGER_PORT['base_url']), json={ |
| 58 | + 'token': token, |
| 59 | + 'password': settings.JUDGER_PORT.get('password'), |
| 60 | + }) |
| 61 | + res_json = res.json() |
| 62 | + except: |
| 63 | + return Response({ |
| 64 | + 'detail': 'Cannot connect to judger port.', |
| 65 | + }, status=status.HTTP_503_SERVICE_UNAVAILABLE) |
| 66 | + else: |
| 67 | + code = res_json.get('code') |
| 68 | + |
| 69 | + if code is None: |
| 70 | + return Response({ |
| 71 | + 'detail': 'Judger Port response format incorrect.' |
| 72 | + }, status=status.HTTP_503_SERVICE_UNAVAILABLE) |
| 73 | + elif code == 4004: |
| 74 | + return Response({ |
| 75 | + 'detail': 'Judger Port don\'t understand our format.\n' |
| 76 | + 'Maybe an upgrade is required.' |
| 77 | + }, status=status.HTTP_503_SERVICE_UNAVAILABLE) |
| 78 | + |
| 79 | + return Response({ |
| 80 | + 'code': 1000, |
| 81 | + 'res': token, |
| 82 | + }, status=status.HTTP_200_OK) |
| 83 | + |
0 commit comments