rest_framework框架

回顾CBV

  什么是CBV

  CBV(class base  view),基于类的视图编程方式,即在view.py文件中使用类的方式为API接口书写对应的视图。与CBV对应的是FBV(function base view),基于函数的视图编程方式。

  CBV的简单示例

# 路由部分
from django.conf.urls import url,include
from . import views

urlpatterns = [
    url(r'^book/$',views.BookSerializers.as_view()),
]

# 视图部分
class BookSerializers(View):

    def get(self,request):
        return HttpResponse("GET")

    def post(self,request):
        return HttpResponse("POST")

 

  

代码分析

as_view部分

 1  @classonlymethod
 2     def as_view(cls, **initkwargs):
 3         """
 4         Main entry point for a request-response process.
 5         """
 6         for key in initkwargs:
 7             if key in cls.http_method_names:
 8                 raise TypeError("You tried to pass in the %s method name as a "
 9                                 "keyword argument to %s(). Don't do that."
10                                 % (key, cls.__name__))
11             if not hasattr(cls, key):
12                 raise TypeError("%s() received an invalid keyword %r. as_view "
13                                 "only accepts arguments that are already "
14                                 "attributes of the class." % (cls.__name__, key))
15 
16         def view(request, *args, **kwargs):
17             self = cls(**initkwargs)
18             if hasattr(self, 'get') and not hasattr(self, 'head'):
19                 self.head = self.get
20             self.request = request
21             self.args = args
22             self.kwargs = kwargs
23             #为捕获到异常,最后实际上就是执行dispatch()方法
24             return self.dispatch(request, *args, **kwargs)
25         view.view_class = cls
26         view.view_initkwargs = initkwargs
27 
28         # take name and docstring from class
29         update_wrapper(view, cls, updated=())
30 
31         # and possible attributes set by decorators
32         # like csrf_exempt from dispatch
33         update_wrapper(view, cls.dispatch, assigned=())
34         return view                    

dispatch部分

1     def dispatch(self, request, *args, **kwargs):
2         # Try to dispatch to the right method; if a method doesn't exist,
3         # defer to the error handler. Also defer to the error handler if the
4         # request method isn't on the approved list.
      #根据请求的方法遍历http_method_names进行匹配,匹配成功返回子类的请求方法的方法名,供路由去执行该方法
5         if request.method.lower() in self.http_method_names:
6             handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
7         else:
8             handler = self.http_method_not_allowed
9         return handler(request, *args, **kwargs)

rest_framework

什么是rest_framework

  是一个前后端分离的框架系统,使前、后端开发着可以脱离对方的工作,从而只考虑自己业务内容的代码逻辑的一个框架。

get方法代码示例

 1 from django.shortcuts import render,HttpResponse
 2 from django.views import View
 3 from . import models
 4 # Create your views here.
 5 
 6 """
 7     使用CBV的方式进行视图编程
 8 """
 9 
10 from rest_framework import serializers
11 
12 
13 # 仿照form的思想,组装成Serializers的数据形式,为后面的序列化类最准备
14 class BookSerializers(serializers.Serializer):
15         title=serializers.CharField(max_length=32)
16         price=serializers.IntegerField()
17         pub_date=serializers.DateField()
18         #  一对多字段,source定义关联表的具体字段
19         publish=serializers.CharField(source="publish.pk")
20         # 多对多字段,采用自定义方法的方式定义显示的字段
21         authors = serializers.SerializerMethodField()
22 
23         #  自定义函数名= get_ + authors,ob代表当前的book对象
24         def get_authors(self,obj):
25             temp=[]
26             for author in obj.authors.all():
27                 temp.append({"pk":author.pk,"name":author.name})
28             return temp
29 
30 
31 from rest_framework.response import Response
32 from rest_framework.views import APIView
33 
34 
35 """
36     功能:
37         向客户端返回http请求
38     知识点:
39         使用rest_framework组件,返回http请求,必须要继承 rest_framework的 APIView,不再继承Django的View
40 """
41 class BookView(APIView):
42 
43     def get(self,request):
44         # 拿到一个QuerySet对象,包含着所有的book对象
45         book_query = models.Book.objects.all()
46         """
47             功能:
48                 声明要对哪些对象的哪些字段进行序列化
49             参数说明:
50                 当只是对一个对象进行序列话的时候,many=FALSE,但是对多个对象进行序列化的时候需要many=True
51         """
52         response = BookSerializers(book_query,many=True)
53         # 序列化的结果保存在data方法中
54         # 使用rest_framework的serializers进行序列化之后的json字符串,需要用Response方法返回
55         return Response(response.data)

对于 BookSerializers 类可以改变继承的类,减少代码

 1 """
 2     方式二:
 3         继承serializers.ModelSerializer类,组装数据格式。
 4         与ModelForm做类比
 5 """
 6 class BookSerializers(serializers.ModelSerializer):
 7     class Meta:
 8         model=models.Book
 9         fields="__all__"
10 
11     authors = serializers.SerializerMethodField()
12     def get_authors(self,obj):
13         temp=[]
14         for author in obj.authors.all():
15             temp.append({"pk":author.pk,"name":author.name})
16         return temp

 

posted on 2018-04-08 18:46  云烟||成雨  阅读(169)  评论(0编辑  收藏  举报