每日作业 7/8

1 自己封装一个MyResponse对象,使用方法如下

return CoomonResponse('100','成功',boo_ser.data)
return CoomonResponse('101','验证失败',boo_ser.errors)

myresponse.py

from rest_framework.response import Response


class MyResponse(Response):
    def __init__(self, status=0, msg='ok', http_status=None, headers=None, exception=False, content_type=None,
                 **kwargs):
        data = {
            'status': status,
            'msg': msg
        }
        # 在外界数据可以用result和results来存储
        if kwargs:
            data.update(kwargs)
        super().__init__(data=data, headers=headers, exception=exception, content_type=content_type)

views.py

from rest_framework.views import APIView
from .models import Book
from app01.serializers import BookSerializer
from app01.myresponse import MyResponse

# 基于APIView写的
class BookView(APIView):
    def get(self, request):
        book_list = Book.objects.all()
        serializer = BookSerializer(instance=book_list, many=True)
        return MyResponse(200, "获取成功", result=serializer.data)

urls.py

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', views.BookView.as_view()),
]

执行效果

 

posted @ 2020-07-09 03:05  耗油炒白菜  阅读(149)  评论(0编辑  收藏  举报