符合RESTful规范的API
统一使用的utils,serializers:
class BaseResponse: def __init__(self): self.code = 1000 self.data = None self.error = None @property def dict(self): return self.__dict__
版本1:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.conf.urls import url from api.views import course from api import views urlpatterns = [ url(r"courses/$",course.CoursesView.as_view()), url(r"courses/(?P<pk>\d+)/$",course.CourseDetailView.as_view()), ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import HttpResponse from rest_framework.views import APIView from rest_framework.versioning import URLPathVersioning from rest_framework.response import Response from api.serializers import course from api import models from api.utils.response import BaseResponse from rest_framework.pagination import PageNumberPagination class CoursesView(APIView): def get(self,request,*args,**kwargs): result = BaseResponse() try: queryset = models.Course.objects.all() # 分页 page = PageNumberPagination() course_list = page.paginate_queryset(queryset,request,self) # 分页之后的结果执行序列化 # 分页之后必须在序列化类中加上:instance=course_list ser = course.CourseSerializers(instance=course_list,many=True) # ser_obj = course.CourseSerializers(queryset,many=True) result.data = ser.data # result.data = ser_obj.data except Exception as e: result.code = 500 result.error = "无法获取数据" return Response(result.dict) class CourseDetailView(APIView): def get(self,request,pk,*args,**kwargs): result = BaseResponse() try: course_obj = models.Course.objects.get(id=pk) ser_obj = course.CourseSerializers(instance=course_obj) result.data = ser_obj.data except Exception as e: result.code = 500 result.error = "无法获取数据" return Response(result.dict)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# from rest_framework.viewsets import ModelViewSet from rest_framework import serializers from api import models class CourseSerializers(serializers.ModelSerializer): level = serializers.CharField(source="get_level_display") class Meta: model = models.Course fields = "__all__" depth = 5 class DegreeSerializers(serializers.ModelSerializer): teacher_name = serializers.SerializerMethodField() # teacher_name = serializers.CharField(source="teachers.") class Meta: model = models.DegreeCourse fields = ["name","teacher_name"] def get_teacher_name(self,row): teacher_list = row.teachers.all() return [{"name": i.name } for i in teacher_list] class DegreeScholarSerializers(serializers.ModelSerializer): # scholar = serializers.CharField(source="scholarship_set.all") scholar = serializers.SerializerMethodField() class Meta: model = models.DegreeCourse fields = ["name","scholar"] def get_scholar(self,row): scholar_list = row.scholarship_set.all() return [{"scholar": i.value} for i in scholar_list] class DegreeMokuaiSerializers(serializers.ModelSerializer): # degree_mokuai = serializers.CharField(source="") # print(111) class Meta: model = models.DegreeCourse fields = ["name"] # fields = "__all__" class Course_Serializers(serializers.ModelSerializer): level = serializers.CharField(source="get_level_display") why_study = serializers.CharField(source="coursedetail.why_study") what_to_study_brief = serializers.CharField(source="coursedetail.what_to_study_brief") recommend_courses = serializers.SerializerMethodField() class Meta: model = models.Course fields = ["name","level","why_study","what_to_study_brief","recommend_courses"] def get_recommend_courses(self,row): recomment_list = row.coursedetail.recommend_courses.all() return [{"id":item.id,"name":item.name} for item in recomment_list] class CourseQuestionSerializer(serializers.ModelSerializer): # question = serializers.CharField(source="asked_question.all") question = serializers.SerializerMethodField() class Meta: model = models.Course fields = ["name","question"] def get_question(self,row): question_list = row.asked_question.all() return [{"question":i.question,"answer":i.answer} for i in question_list] class CourseOutlineSerializers(serializers.ModelSerializer): courseoutline = serializers.SerializerMethodField() class Meta: model = models.Course fields = ["name","courseoutline"] # fields = "__all__" def get_courseoutline(self,row): outline_list = row.coursedetail.courseoutline_set.all() return [{"courseoutline":i.title,"content":i.content} for i in outline_list] class CourseChapterSerializers(serializers.ModelSerializer): course_chapter = serializers.SerializerMethodField() class Meta: model = models.Course fields = ["name","course_chapter"] def get_course_chapter(self,row): course_chapter_list = row.coursechapters.all() return [{"chapter": i.name} for i in course_chapter_list]
版本2:
urls:
from django.conf.urls import url from api.views import course from api import views urlpatterns = [ # 如果as_view()里面要传参数的话,前提视图CBV必须继承 ViewSetMixin ,这样才能往as_view()中传入参数。 # 键值对的形式,表明了各请求方式对应的方法,所以特定的请求方式,便可执行相应的方法。 # 如果as_view()里写了相应的键值对,在视图CBV中必须写出相应的方法。 url(r'courses/$',course.CoursesView.as_view({'get':'list','post':'create'})), url(r'courses/(?P<pk>\d+)/$',course.CoursesView.as_view({'get':'retrieve','put':'update','delete':'destroy'})) ]
views:
from django.shortcuts import HttpResponse from rest_framework.views import APIView from rest_framework.versioning import URLPathVersioning from rest_framework.response import Response from api.serializers import course from api import models from api.utils.response import BaseResponse from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import ViewSetMixin # 继承ViewSetMixin class CoursesView(ViewSetMixin,APIView): def list(self,request,*args,**kwargs): result = BaseResponse() try: # 从数据库中获取数据 queryset = models.Course.objects.all() ser_obj = course.CourseSerializers(queryset,many=True) result.data = ser_obj.data except Exception as e: result.code = 500 result.error = "无法获取数据" return Response(result.dict) def create(self,request,*args,**kwargs): ''' post方式,增加 :param request: :param args: :param kwargs: :return: ''' def retrieve(self,request,pk,*args,**kwargs): ''' 详细显示 :param request: :param pk: :param args: :param kwargs: :return: ''' result = BaseResponse() try: course_obj = models.Course.objects.get(id=pk) ser_obj = course.CourseSerializers(instance=course_obj) # print(ser_obj) result.data = ser_obj.data # print(result.data) except Exception as e: result.code = 500 result.error = "无法获取数据" return Response(result.dict) def update(self,pk,*args,**kwargs): ''' put,更改 :param pk: :param args: :param kwargs: :return: ''' def destroy(self,pk,*args,**kwargs): ''' delete ,删除 :param pk: :param args: :param kwargs: :return: '''
版本3:
urls:
from django.conf.urls import url from api.views import course from api import views urlpatterns = [ # 如果as_view()里面要传参数的话,前提视图CBV必须继承 ViewSetMixin ,这样才能往as_view()中传入参数。 # 键值对的形式,表明了各请求方式对应的方法,所以特定的请求方式,便可执行相应的方法。 # 如果as_view()里写了相应的键值对,在视图CBV中必须写出相应的方法。 url(r'courses/$',course.CoursesView.as_view({'get':'list'})), url(r'courses/(?P<pk>\d+)/$',course.CoursesView.as_view({'get':'retrieve'})) ]
views:
from django.shortcuts import HttpResponse from rest_framework.views import APIView from rest_framework.versioning import URLPathVersioning from rest_framework.response import Response from api.serializers import course from api import models from api.utils.response import BaseResponse from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import ViewSetMixin from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,ListModelMixin from rest_framework.viewsets import GenericViewSet class CoursesView(ListModelMixin,GenericViewSet): queryset = models.Course.objects.all() def list(self,request,*args,**kwargs): result = BaseResponse() try: course_list = models.Course.objects.all() ser_obj = course.CourseSerializers(course_list,many=True) result.data = ser_obj.data except Exception as e: result.code = 500 result.error = "无法获取数据" return Response(result.dict) def retrieve(self,request,pk,*args,**kwargs): result = BaseResponse() try: course_obj = models.Course.objects.get(id=pk) ser_obj = course.CourseSerializers(course_obj) result.data = ser_obj.data except Exception as e: result.code = 500 result.error = "无法获取数据" return Response(result.dict)