Restful_프레임워크 보기 구성 요소 코드 실례 분석

1. 기본 보기
출판사의 첨삭을 써서resful 인터페이스를 고치다
django 프로젝트를 미리 만들고 테이블을 만들고 기록을 추가해야 합니다
라우팅:
url(r'^publish/$', views.PublishView.as_view()),
url(r'^publish/(?P\d+)/$', views.PublishDetailView.as_view()),
보기:

from api import modelsfrom rest_framework import serializersfrom rest_framework.response import Responsefrom rest_framework.views import APIView
class PublishSerializers(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'

class PublishView(APIView):
  # 
  def get(self, request):
    publish_list = models.Publish.objects.all()
    bs = PublishSerializers(publish_list, many=True)
    #  

    return Response(bs.data)  # 
  
  def post(self, request):
    #  
    print(request.data)

    bs=PublishSerializers(data=request.data)
    if bs.is_valid():
      bs.save() #  
      return Response(bs.data)  # 
    else:

      return Response(bs.errors)

class PublishDetailView(APIView):   # 
  def get(self,request,pk):
    publish_obj=models.Publish.objects.filter(pk=pk).first()
    bs=PublishSerializers(publish_obj,many=False)
    return Response(bs.data)   # 
  def put(self,request,pk):
    publish_obj = models.Publish.objects.filter(pk=pk).first()

    bs=PublishSerializers(data=request.data,instance=publish_obj)
    if bs.is_valid():
      bs.save() # update
      return Response(bs.data)
    else:
      return Response(bs.errors)   # 
  def delete(self,request,pk):
    models.Publish.objects.filter(pk=pk).delete()

    return Response("")
2. mixins 클래스와generic 클래스 작성 보기
라우팅:
url(r'^publishes$', views.Publish.as_view()),
url(r'^publish/(?P\d+)', views.PublishDetail.as_view()),
보기:

from api import models
from rest_framework import serializers
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
class PublishSer(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'
class Publish(GenericAPIView,mixins.ListModelMixin,mixins.CreateModelMixin):
  queryset = models.Publish.objects.all()
  serializer_class = PublishSer
  def get(self,request):
    return self.list(request)  # ListModelMixin list , :Response(serializer.data)
  def post(self,request):
    return self.create(request) # , , 
class PublishDetail(GenericAPIView,mixins.DestroyModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin):

  queryset = models.Publish.objects.all()
  serializer_class = PublishSer
  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)
3. generic 아래 ListCreateAPIVIew 및 RetrieveUpdateDestroyAPIVIew 사용
라우팅:
url(r'^publishes$', views.Publish.as_view()),
url(r'^publish/(?P\d+)', views.PublishDetail.as_view()),
보기:

from api import models
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework import serializers
class Publishser(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'

class Publish(ListCreateAPIView):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser

class PublishDetail(RetrieveUpdateDestroyAPIView):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser
4. ModelViewSet 사용
라우팅:
url(r'^publish$',views.Publish.as_view({'get':'list','post':'create'})),
url(r'^publish/(?P\d+)', views.Publish.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
보기:

from rest_framework.viewsets import ModelViewSet
from api import models
from rest_framework import serializers
class Publishser(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'
class Publish(ModelViewSet):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기