Permalink
Browse files

API view

  • Loading branch information...
junkboy0315 committed Feb 8, 2019
1 parent 297871c commit 86b1b87abb5967064feb7eaa12911beca388b244
Showing with 17 additions and 17 deletions.
  1. +17 −17 tutorial/snippets/views.py
@@ -1,12 +1,12 @@
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer


@csrf_exempt
@api_view(['GET', 'POST'])
def snippet_list(request):
"""
- 全ての snippets を表示する。
@@ -15,39 +15,39 @@ def snippet_list(request):
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
return Response(serializer.data)

elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data)
serializer = SnippetSerializer(data=request.data)
if not serializer.is_valid():
return JsonResponse(serializer.errors, status=400)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return JsonResponse(serializer.data, status=201)
return Response(serializer.data, status=status.HTTP_201_CREATED)


@csrf_exempt
@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
"""
単一のスニペットの、取得・更新・削除を行う。
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
return Response(status=status.HTTP_404_NOT_FOUND)

if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return JsonResponse(serializer.data)
return Response(serializer.data)

elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SnippetSerializer(snippet, data=data)
serializer = SnippetSerializer(snippet, data=request.data)
if not serializer.is_valid():
return JsonResponse(serializer.errors, status=400)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return JsonResponse(serializer.data)
return Response(serializer.data)

elif request.method == 'DELETE':
snippet.delete()
return HttpResponse(status=204)
return Response(status=status.HTTP_204_NO_CONTENT)

0 comments on commit 86b1b87

Please sign in to comment.