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控制

 

解析器

響應器

 

 

模板文件查找順序

-先從項目中找python

相關文章
相關標籤/搜索