Day 13

TIL - Django REST framework

๐Ÿ“‹ย ๊ณต๋ถ€ ๋‚ด์šฉ

Django REST framework

install

settings.py

1
2
3
4
5
...
INSTALLED_APPS = [
...
    "rest_framework",
]

Serializer

Serializer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from rest_framework import serializers
from polls.models import Question
class QuestionSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    question_text = serializers.CharField(max_length=200)
    pub_date = serializers.DateTimeField(read_only=True)

    def create(self, validated_data):
        return Question.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.question_text = (
            validated_data.get("question_text", instance.question_text)
            + "[์‹œ๋ฆฌ์–ผ๋ผ์ด์ €์—์„œ ์—…๋ฐ์ดํŠธ]"
        )
        # id, pub_date๋Š” Readonly๋ผ ์—…๋ฐ์ดํŠธ ํ•˜์ง€ ์•Š์Œ
        instance.save()
        return instance

ModelSerializer

1
2
3
4
5
6
from rest_framework import serializers
from polls.models import Question
class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ["id", "question_text", "pub_date"]

Views

CRUD in HTTPS

Method ๊ธฐ๋ฐ˜

  • URL Conf

    • mysite/ursl.py
    1
    2
    3
    4
    5
    6
    7
    8
    
    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("polls/", include("polls.urls")),
        path("rest/", include("polls_api.urls")),
    ]
    
    • polls_api/urls.py
    1
    2
    3
    4
    5
    6
    7
    
    from django.urls import path
    from .views import *
    
    urlpatterns = [
        path("question/", question_list, name="question-list"),
        path("question/<int:id>/", question_detail, name="question-detail"),
    ]
    
  • GET

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from polls.models import Question
from polls_api.serializers import QuestionSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view
# ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ ์•„๋ฌด๊ฒƒ๋„ ๋„ฃ์ง€ ์•Š์œผ๋ฉด 'GET'
@api_view()
def question_list(request):
    questions = Question.objects.all()
    # ์—ฌ๋Ÿฌ๊ฐœ์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ์ค„ ๋•Œ Many ์˜ต์…˜
    serializer = QuestionSerializer(questions, many=True)
    return Response(serializer.data)
  • POST
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
...
from rest_framework import status
@api_view(["GET", "POST"])
def question_list(request):
...
    if request.method == "POST":
        serializer = QuestionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  • PUT & DELETE
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
...
from django.shortcuts import get_object_or_404
@api_view(["GET", "PUT", "DELETE"])
def question_detail(request, id):
    question = get_object_or_404(Question, pk=id)

    if request.method == "GET":
        serializer = QuestionSerializer(question)
        return Response(serializer.data)

    if request.method == "PUT":
        serializer = QuestionSerializer(question, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    if request.method == "DELETE":
        question.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

Class ๊ธฐ๋ฐ˜

  • APIView
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
...
from rest_framework.views import APIView

class QuestionList(APIView):
    def get(self, request):
        questions = Question.objects.all()
        serializer = QuestionSerializer(questions, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = QuestionSerializer(data=request.data)
        print(type(request.data))
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class QuestionDetail(APIView):
    def get(self, request, id):
        question = get_object_or_404(Question, pk=id)
        serializer = QuestionSerializer(question)
        return Response(serializer.data)

    def put(self, request, id):
        question = get_object_or_404(Question, pk=id)
        serializer = QuestionSerializer(question, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, id):
        question = get_object_or_404(Question, pk=id)
        question.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
  • URL Conf : polls_api/urls.py
1
2
3
4
5
...
urlpatterns = [
    path("question/", QuestionList.as_view(), name="question-list"),
    path("question/<int:id>/", QuestionDetail.as_view(), name="question-detail"),
]
  • Mixin
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class QuestionList(
    mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)


class QuestionDetail(
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    generics.GenericAPIView,
):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)
    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)
    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)
  • URL Conf : polls_api/urls.py
1
2
3
4
5
...
urlpatterns = [
    path("question/", QuestionList.as_view(), name="question-list"),
    path("question/<int:pk>/", QuestionDetail.as_view(), name="question-detail"),
]
  • Generic API View
1
2
3
4
5
6
7
class QuestionList(generics.ListCreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

class QuestionDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
  • URL Conf : polls_api/urls.py
1
2
3
4
5
...
urlpatterns = [
    path("question/", QuestionList.as_view(), name="question-list"),
    path("question/<int:pk>/", QuestionDetail.as_view(), name="question-detail"),
]

๐Ÿ‘€ย CHECK

(์–ด๋ ต๊ฑฐ๋‚˜ ์ƒˆ๋กญ๊ฒŒ ์•Œ๊ฒŒ ๋œ ๊ฒƒ ๋“ฑ ๋‹ค์‹œ ํ™•์ธํ•  ๊ฒƒ๋“ค)

โ— ๋Š๋‚€ ์ 

Hugo๋กœ ๋งŒ๋“ฆ
Jimmy์˜ Stack ํ…Œ๋งˆ ์‚ฌ์šฉ ์ค‘