Django-DRF-图书增删改查 !!!

 

自己封装的

class MyResponse():
    def __init__(self):
        self.status = 100
        self.msg = None

    @property
    def get_dic(self):
        return self.__dict__


# 自己封装的
# class List():
#     def get_list(self, request):
#         response = MyResponse()
#         book_list = self.model.objects.all()
#         book_ser = self.serializer(instance=book_list, many=True)
#         print(book_ser.data)
#         response.books = book_ser.data
#         return Response(response.get_dic)
#
#
# class ObjSave():
#     def save(self, request):
#         response = MyResponse()
#         book_ser = self.serializer(data=request.data)
#         if book_ser.is_valid():
#             book_ser.save()
#         else:
#             response.status = 101
#             response.msg = book_ser.errors
#         return Response(response.get_dic)
#
#
# class Books(List, ObjSave, APIView):
#     model = models.Book
#     serializer = BookSerializer
#
#     def get(self, request):
#         return self.get_list(request)
#
#     def post(self, request):
#         return self.save(request)
#
#
# class Publishs(List, ObjSave, APIView):
#     model = models.Publish
#     serializer = PublishSer
#
#     def get(self, request):
#         return self.get_list(request)
#
#     def post(self, request):
#         return self.save(request)
#
#
# from django.core.exceptions import ObjectDoesNotExist
#
#
# class Book(APIView):
#     def get(self, request, id):
#         response = MyResponse()
#         try:
#             book = models.Book.objects.get(pk=id)
#             book_ser = BookSerializer(instance=book, many=False)
#             response.book = book_ser.data
#         except ObjectDoesNotExist as  e:
#             response.status = 101
#             response.msg = 'id不存在'
#
#         except Exception as e:
#             print(e)
#             response.status = 201
#             # response.msg = '您的操作有误'
#             response.msg = str(e)
#         return Response(response.get_dic)
#
#     def put(self, request, id):
#         response = MyResponse()
#         try:
#             book = models.Book.objects.get(pk=id)
#             book_ser = BookSerializer(data=request.data, instance=book)
#             if not book_ser.is_valid():
#                 raise Exception('数据校验失败')
#             book_ser.save()
#             response.book = book_ser.data
#             response.msg = '修改成功'
#         except ObjectDoesNotExist as  e:
#             response.status = 101
#             response.msg = 'id不存在'
#
#         except Exception as e:
#             print(e)
#             response.status = 201
#             # response.msg = '您的操作有误'
#             response.msg = str(e)
#         return Response(response.get_dic)
#
#     def delete(self, request, id):
#         response = MyResponse()
#         try:
#             models.Book.objects.filter(pk=id).delete()
#             response.msg = '删除成功'
#         except Exception as e:
#             print(e)
#             response.status = 201
#             # response.msg = '您的操作有误'
#             response.msg = str(e)
#         return Response(response.get_dic)

  

drf帮咱封装的

 

# drf帮咱封装的
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, ListModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework.generics import GenericAPIView

# class Publishs(GenericAPIView, CreateModelMixin, ListModelMixin):
#     queryset = models.Publish.objects
#     serializer_class = PublishSer
#
#     def get(self, request):
#         return self.list(request)
#
#     def post(self, request):
#         return self.create(request)

# DestroyModelMixin:删除
#  UpdateModelMixin,:更新
# RetrieveModelMixin :获取一条
# CreateModelMixin:新增一条
#  ListModelMixin:获取所有
# class Publish(GenericAPIView, DestroyModelMixin, UpdateModelMixin, RetrieveModelMixin):
#     queryset = models.Publish.objects
#     serializer_class = PublishSer
#     lookup_field='id'
#
#     def get(self, request, *args, **kwargs):
#         return self.retrieve(request, *args, **kwargs)
#
#     def delete(self, request, *args, **kwargs):
#         return self.destroy(request, *args, **kwargs)
#
#     def put(self, request, *args, **kwargs):
#         return self.update(request, *args, **kwargs)

# from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, CreateAPIView, ListAPIView, \
#     RetrieveAPIView, RetrieveUpdateAPIView, DestroyAPIView
#
# #
# class Publishs(ListCreateAPIView):
#     queryset = models.Publish.objects.all()
#     serializer_class = PublishSer
#
#
# class Publish(RetrieveUpdateDestroyAPIView):
#     queryset = models.Publish.objects.all()
#     serializer_class = PublishSer
from  rest_framework.parsers import JSONParser
from  rest_framework.parsers import FormParser
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from  rest_framework.renderers import JSONRenderer
class PublishView(ModelViewSet):
    # renderer_classes=[JSONRenderer,]
    parser_classes=[JSONParser,FormParser]
    queryset=models.Publish.objects.all()
    serializer_class=PublishSer

ViewSetMixin 重写了as_view方法

from rest_framework.viewsets import ViewSetMixin
# ViewSetMixin 重写了as_view方法

# ViewSetMixin 写在前面,先找ViewSetMixin的as_view方法
# 用了ViewSetMixin ,视图类中,不需要再写get,post,delete....这些函数了,函数名可以自定义
# 而且这个视图类,可以响应多条路由
# class PublishView(ViewSetMixin,APIView):
#     def aaa(self,request):
#
#         return Response({'status':100})
#     def bbb(self,request):
#         return Response({'bb': "bbb"})



# 'DEFAULT_PARSER_CLASSES': (
#     'rest_framework.parsers.JSONParser',
#     'rest_framework.parsers.FormParser',
#     'rest_framework.parsers.MultiPartParser'
# )

 

路由url

from django.conf.urls import url,include
from django.contrib import admin
from app01 import  views
# from rest_framework import routers
# router=routers.DefaultRouter()
# # 两个参数,一个是匹配的路由,一个是视图中写的CBV的类
# router.register('publish',views.PublishView)
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.Login.as_view()),
    # as_view()类的绑定方法
    # url(r'^books/', views.Books.as_view()),
    # url(r'^publishs/', views.Publishs.as_view()),
    # url(r'^publish/(?P<pk>\d+)', views.Publish.as_view()),
    # url(r'^book/(?P<id>\d+)', views.Book.as_view()),
    # MyViewSet.as_view({'get': 'list', 'post': 'create'})
    url(r'^publishs/', views.PublishView.as_view({'get': 'list','post':'create'})),
    # url(r'^publish\.(?P<format>\w+)$', views.PublishView.as_view({'get': 'list','post':'create'})),
    url(r'^publish/(?P<pk>\d+)', views.PublishView.as_view({'get': 'retrieve','put':'update','delete':'destroy'})),

    # 原来的视图类,只能响应一个路由
    # 现在的视图类,可以响应多个路由
    # url(r'^publishs/', views.PublishView.as_view({'get': 'aaa','post':'ddd'})),
    #
    # url(r'^bbb/', views.PublishView.as_view({'get': 'bbb','post':'ccc'})),
    # url(r'', include(router.urls))
]

url控制

 

解析器

响应器

 

 

模板文件查找顺序

-先从项目中找

 

posted @ 2019-02-28 15:05  逐梦~前行  阅读(1407)  评论(0编辑  收藏  举报