-
-
Save Gpzim98/0e9c2ef7b1e43360af4b7d8fcb08e0ec to your computer and use it in GitHub Desktop.
Django Rest Framework views best practices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1 - Ideal DRF View | |
from rest_framework import status | |
from rest_framework.decorators import detail_route | |
from rest_framework.response import Response | |
import logging | |
def do_log(e): | |
logger = logging.getLogger('django') | |
time = datetime.datetime.now() | |
logger.exception(time.strftime("%Y-%m-%d %H:%M:%S") + ' - ' + str(request.user)) | |
@detail_route(methods=['post']) | |
def already_studied_here(self, request, pk=None): | |
try: | |
profile = Profile.objects.get(user=request.user) | |
school = School.objects.get(pk=200) | |
school.new_student(profile) | |
data = {'message': 'Student successfully enrolled'} | |
return Response(data, status=status.HTTP_200_OK) | |
except ValueError: | |
do_log(request.user) | |
data = {'message': 'There was an error during the process: '+str(e)} | |
return Response(data, status=status.HTTP_400_BAD_REQUEST) | |
except IntegrityError: | |
do_log(request.user) | |
data = {'message': 'There was an error during the process: ' + str(e)} | |
return Response(data, status=status.HTTP_400_BAD_REQUEST) | |
except Exception as e: | |
do_log(request.user) | |
data = {'message': 'There was an error during the process: ' + str(e)} | |
return Response(data, status=status.HTTP_400_BAD_REQUEST) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment