完成各种定制的学习

main
RogerWork 1 year ago
parent 5aed96cb02
commit a1e220a67f
  1. 2
      apps/goods/drf_customer_renderer.py
  2. 9
      apps/goods/urls.py
  3. 17
      apps/goods/views_viewset.py
  4. 22
      common/myexception.py
  5. 72
      common/mymodelviewset.py
  6. 6
      common/mypagination.py
  7. 4
      common/myresponse.py
  8. 2
      myshop_back/settings.py

@ -3,7 +3,7 @@ from rest_framework.renderers import JSONRenderer
class CustomRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
print('render11111111111111111111')
print('CustomRenderer')
if renderer_context:
if isinstance(data, dict):
msg = data.pop('msg', 'success')

@ -15,8 +15,9 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include
from apps.goods import views, views_api, views_apiview, views_mixin, views_generics, views_viewset
from rest_framework.routers import DefaultRouter
goods_list = views_viewset.GoodsViewSet.as_view({
'get': 'list',
@ -28,6 +29,10 @@ goods_detail = views_viewset.GoodsViewSet.as_view({
'delete': 'destroy',
})
router = DefaultRouter()
router.register('goods_custom', views_viewset.GoodsViewSetCustom, basename='goods_custom')
urlpatterns = [
# path('cate_index/', views.GoodCateView.as_view(), name='cate_index'),
# path('cate_add/', views.GoodCateAddView.as_view(), name='cate_add'),
@ -46,4 +51,6 @@ urlpatterns = [
path('goods_generics/<pk>/', views_generics.GoodsDetailGenerics.as_view()),
path('goods_viewset/', goods_list),
path('goods_viewset/<pk>/', goods_detail),
path('', include(router.urls))
]

@ -1,12 +1,14 @@
from rest_framework import viewsets
from rest_framework import mixins
from django_filters.rest_framework import DjangoFilterBackend
from django_filters import rest_framework
from rest_framework import filters
from apps.goods.models import Goods
from apps.goods.serializers import GoodsSerializers
from common.mypagination import MyPagination
from common.myfilter import MyFilter
from common.mymodelviewset import MyModelViewSet
class GoodsViewSet(mixins.ListModelMixin,
@ -27,3 +29,18 @@ class GoodsViewSet(mixins.ListModelMixin,
search_fields = ('name', 'price')
# 排序
ordering_fields = ('id', 'name', 'price')
class GoodsDetailViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Goods.objects.all()
serializer_class = GoodsSerializers
class GoodsViewSetCustom(MyModelViewSet, viewsets.GenericViewSet):
queryset = Goods.objects.all()
serializer_class = GoodsSerializers
pagination_class = MyPagination
filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
filterset_class = MyFilter
search_fields = ('name', 'price')
ordering_fields = ('id', 'name', 'price')

@ -0,0 +1,22 @@
from rest_framework.views import exception_handler
def my_exception_handler(exc, context):
response = exception_handler(exc, context)
print('exception_handler')
print(exception_handler)
if response is not None:
response.data['code'] = response.status_code
if response.status_code == 405:
response.data['msg'] = '请求不予许'
elif response.status_code == 401:
response.data['msg'] = '认证未通过'
elif response.status_code == 403:
response.data['msg'] = '禁止访问'
elif response.status_code == 404:
response.data['msg'] = '未找到文件'
elif response.status_code >= 500:
response.data['msg'] = '服务器异常'
else:
response.data['msg'] = '其他未知错误'
return response

@ -0,0 +1,72 @@
from rest_framework.viewsets import ModelViewSet
from rest_framework import status
from common.myresponse import MyResponse
class MyModelViewSet(ModelViewSet):
# CreateModelMixin -> create
def create(self, request, *args, **kwargs):
print(request.data)
serializer = self.get_serializer(data=request.data)
print(serializer)
serializer.is_valid(raise_exception=True)
print(serializer.data)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return MyResponse(data=serializer.data, code=201, msg='OK', status=status.HTTP_201_CREATED, headers=headers)
# ListModelMixin -> list
def list(self, request, *args, **kwargs):
print('self.get_queryset()')
print(self.get_queryset())
queryset = self.filter_queryset(self.get_queryset())
print('queryset')
print(queryset)
page = self.paginate_queryset(queryset)
print('page')
print(page)
if page is not None:
serializer = self.get_serializer(page, many=True)
print('serializer')
print(serializer)
print('serializer.data')
print(serializer.data)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
print('serializer')
print(serializer)
print('serializer.data')
print(serializer.data)
return MyResponse(data=serializer.data, code=200, msg='OK', status=status.HTTP_200_OK)
# RetrieveModelMixin -> retrieve
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
print(instance)
serializer = self.get_serializer(instance)
print(serializer)
return MyResponse(data=serializer.data, code=200, msg='OK', status=status.HTTP_200_OK)
# UpdateModelMixin -> update
def update(self, request, *args, **kwargs):
print(kwargs)
partial = kwargs.pop('partial', False)
print(partial)
instance = self.get_object()
print(instance)
print(request.data)
serializer = self.get_serializer(instance, data=request.data, partial=partial)
print(serializer)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
instance._prefetched_objects_cache = {}
return MyResponse(data=serializer.data, code=200, msg='OK', status=status.HTTP_200_OK)
# DestroyModelMixin -> destroy
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return MyResponse(data=[], code=200, msg='OK', status=status.HTTP_204_NO_CONTENT)

@ -1,4 +1,6 @@
from rest_framework.pagination import PageNumberPagination
from rest_framework import status
from common.myresponse import MyResponse
class MyPagination(PageNumberPagination):
@ -6,3 +8,7 @@ class MyPagination(PageNumberPagination):
max_page_size = 5
page_size_query_param = 'size'
page_query_param = 'page'
def get_paginated_response(self, data):
return MyResponse(data=data, code=200, msg='OK', status=status.HTTP_200_OK, count=self.page.paginator.count,
next=self.get_next_link(), previous=self.get_previous_link())

@ -16,9 +16,11 @@ class MyResponse(Response):
)
raise AssertionError(msg)
self.data = dict(code=code, status=status, data=data)
self.data = dict(code=code, status=status, msg=msg, data=data)
print('MyResponse-kwargs')
print(kwargs)
self.data.update(kwargs)
print('MyResponse-self.data')
print(self.data)
self.template_name = template_name
self.exception = exception

@ -13,7 +13,6 @@ https://docs.djangoproject.com/en/4.2/ref/settings/
from pathlib import Path
import sys, os
import rest_framework.filters
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
@ -159,4 +158,5 @@ REST_FRAMEWORK = {
'PAGE_SIZE': 5,
# 设置筛选模板
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'EXCEPTION_HANDLER': 'common.myexception.my_exception_handler',
}

Loading…
Cancel
Save