drf Introduction and some source code analysis

review

"""
1、vue如果控制html
    在html中设置挂载点、导入vue.js环境、创建Vue对象与挂载点绑定
    
2、vue是渐进式js框架

3、vue指令
    {{ }}
    v-text|html => 限制一次性渲染 v-once
    v-if|show
    v-if v-else-if v-else
    v-for
    v-model
    v-bind  [c1, c2] | {active: isActive}
    v-on fn | fn(...) | fn($event, ...)
    
    {{ data中出现的变量 }}  v-if="data中出现的变量 的条件表达式"
    
4、vue实例成员
    el | template
    components
    data {} | data () { return {} }
    methods
    computed:定义的是方法属性
    watch:监听属性
    props
    
    <div id="app">
        <Nav :subdata="supdata" @subaction="supaction"></Nav>
    </div>
    
5、生命周期钩子
    都是实例成员,在组件创建到销毁整个过程的某些时间节点回调的函数
    
    beforeCreated() {
        this._fn => this.$option.methods._fn
    }
    
6、项目
    环境:node => npm(cnpm) => vue/cli
    创建与配置 vue create proj | 选择基础插件 | 配置npm启动
    插件:vue-router | vuex | axios | vue-cookies | element-ui
"""

drf framework

Full name: django-rest framework

Knowledge Point

"""
1、接口:什么是接口、restful接口规范
2、CBV生命周期源码 - 基于restful规范下的CBV接口
3、请求组件、解析组件、响应组件
4、序列化组件(灵魂)
5、三大认证(重中之重):认证、权限(权限六表)、频率
6、其他组件:过滤、筛选、排序、分页、路由
"""

# 难点:源码分析

interface

"""
接口:联系两个物质的媒介,完成信息交互
web程序中:联系前台页面与后台数据库的媒介
web接口组成:
    url:长得像放回数据的url链接
    请求参数:前台按照指定的key提供数据给后台
    响应数据:后台与数据库交互后将数据反馈给前台
"""

restful Interface Specification

Interface Specification: background is to use different languages, the same interface can be used to obtain the same data

How to write: Interface specification is a standardized interface to write, write, write interfaces url, response data

Note: If the request parameter also into account the scope of that interface documentation in writing

Two parts:

  • url
1) 用api关键字标识接口url
    api.baidu.com | www.baidu.com/api
    
2) 接口数据安全性决定优先选择https协议

3) 如果一个接口有多版本存在,需要在url中标识体现
    api.baidu.com/v1/... | api.baidu.com/v2/...
    
4) 接口操作的数据源称之为 资源,在url中一般采用资源复数形式,一个接口可以概括对该资源的多种操作方式
    api.baidu.com/books | api.baidu.com/books/(pk)
    
5) 请求方式有多种,用一个url处理如何保证不混乱 - 通过请求方式标识操作资源的方式
    /books      get         获取所有
    /books      post        增加一个(多个)
    /books/(pk) delete      删除一个
    /books/(pk) put         整体更新一个
    /books/(pk) patch       局部更新一个

6) 资源往往涉及数据的各种操作方式 - 筛选、排序、限制
    api.baidu.com/books/?search=西&ordering=-price&limit=3
  • Response Data
1) http请求的响应会有响应状态码,接口用来返回操作的资源数据,可以拥有 操作数据结果的 状态码
    status  0(操作资源成功)  1(操作资源失败)  2(操作资源成功,但没匹配结果)
    注:资源状态码不像http状态码,一般都是后台与前台或是客户约定的
    
2) 资源的状态码文字提示
    status  ok  '账号有误'  '密码有误'  '用户锁定'
    
3) 资源本身
    results
    注:删除资源成功不做任何数据返回(返回空字符串)
    
4) 不能直接放回的资源(子资源、图片、视频等资源),返回该资源的url链接

Based Native Interface restful specification Django

Main routes: url.py
from django.conf.urls import url, include
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 路由分发
    url(r'^api/', include('api.urls'))
]
Api sub-assembly route: api / url.py
from django.conf.urls import url

from . import views
urlpatterns = [
    url(r'^books/', views.Book.as_view()),
    url(r'^books/(?P<pk>.*)/$', views.Book.as_view()),
]
Model layer: model.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=64)
    price = models.DecimalField(max_digits=5, decimal_places=2)

    class Meta:
        db_table = 'old_boy_book'
        verbose_name = '书籍'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '《%s》' % self.title
Background layer: admin.py
from django.contrib import admin

from . import models

admin.site.register(models.Book)
Database Migration
>: python manage.py makemigrations
>: python manage.py migrrate

>: python manage.py createsuperuser
View layer: views.py
from django.http import JsonResponse

from django.views import View
from . import models


# 六大基础接口:获取一个 获取所有 增加一个 删除一个 整体更新一个 局部更新一个
# 十大接口:群增 群删 整体改群改 局部改群改
class Book(View):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if not pk:  # 群查
            # 操作数据库
            book_obj_list = models.Book.objects.all()
            # 序列化过程
            book_list = []
            for obj in book_obj_list:
                dic = {}
                dic['title'] = obj.title
                dic['price'] = obj.price
                book_list.append(dic)
            # 响应数据
            return JsonResponse({
                'status': 0,
                'msg': 'ok',
                'results': book_list
            }, json_dumps_params={'ensure_ascii': False})
        else:  # 单查
            book_dic = models.Book.objects.filter(pk=pk).values('title', 'price').first()
            if book_dic:
                return JsonResponse({
                    'status': 0,
                    'msg': 'ok',
                    'results': book_dic
                }, json_dumps_params={'ensure_ascii': False})
            return JsonResponse({
                'status': 2,
                'msg': '无结果',
            }, json_dumps_params={'ensure_ascii': False})


    # postman可以完成不同方式的请求:get | post | put ...
    # postman发送数据包有三种方式:form-data | urlencoding | json
    # 原生django对urlencoding方式数据兼容最好
    def post(self, request, *args, **kwargs):
        # 前台通过urlencoding方式提交数据
        try:
            book_obj = models.Book.objects.create(**request.POST.dict())
            if book_obj:
                return JsonResponse({
                    'status': 0,
                    'msg': 'ok',
                    'results': {'title': book_obj.title, 'price': book_obj.price}
                }, json_dumps_params={'ensure_ascii': False})
        except:
            return JsonResponse({
                'status': 1,
                'msg': '参数有误',
            }, json_dumps_params={'ensure_ascii': False})

        return JsonResponse({
            'status': 2,
            'msg': '新增失败',
        }, json_dumps_params={'ensure_ascii': False})

Postman Interface Tool

The official website to download and install

get request carries parameter takes Params

other post request, submit data packets can be used in three ways: form-date, urlencoding, json

All requests can carry the request header









Code

important point:

1. The filtering criteria are returned get the object, it can not later point value ,, filter was querySet object may point method querySet

2. The default browser is get access request

3.post request must inject out csrf

4.create is the return of objects

5.request.POST.dict () is dict () method request.POST QuerySet object data into a dictionary form

Response default 6.rest_framework is the browser returns a page, postman returned data

Using the route distribution (under api also create a url.py), then view class view to write, then write models.py model, data migration, create createsuperuser, the background to the admin data entry, and then download pip3 install djangorestframework, then app settings registered in 'rest_framework', as well as post request to talk settings in csrf note off

项目dp_proj下的url.py
from django.conf.urls import url, include
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 路由分发
    url(r'^api/', include('api.urls'))
]
应用api下的urls.py
from django.conf.urls import url

from . import views
urlpatterns = [
    url(r'^books/$', views.Book.as_view()),
    url(r'^books/(?P<pk>.*)/$', views.Book.as_view()),

    url(r'^test/$', views.Test.as_view()),
    url(r'^test2/$', views.Test2.as_view()),
]
models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=64)
    price = models.DecimalField(max_digits=5, decimal_places=2)

    class Meta:
        db_table = 'old_boy_book'
        verbose_name = '书籍'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '《%s》' % self.title
admin.py
from django.contrib import admin

from . import models

admin.site.register(models.Book)
views.py

from django.http import JsonResponse

from django.views import View
from . import models


# 六大基础接口:获取一个 获取所有 增加一个 删除一个 整体更新一个 局部更新一个
# 十大接口:群增 群删 整体改群改 局部改群改
class Book(View):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if not pk:  # 群查
            # 操作数据库
            book_obj_list = models.Book.objects.all()
            # 序列化过程
            book_list = []
            for obj in book_obj_list:
                dic = {}
                dic['title'] = obj.title
                dic['price'] = obj.price
                book_list.append(dic)
            # 响应数据
            return JsonResponse({
                'status': 0,
                'msg': 'ok',
                'results': book_list
            }, json_dumps_params={'ensure_ascii': False})
        else:  # 单查
            book_dic = models.Book.objects.filter(pk=pk).values('title', 'price').first()
            if book_dic:
                return JsonResponse({
                    'status': 0,
                    'msg': 'ok',
                    'results': book_dic
                }, json_dumps_params={'ensure_ascii': False})
            return JsonResponse({
                'status': 2,
                'msg': '无结果',
            }, json_dumps_params={'ensure_ascii': False})


    # postman可以完成不同方式的请求:get | post | put ...
    # postman发送数据包有三种方式:form-data | urlencoding | json
    # 原生django对urlencoding方式数据兼容最好
    def post(self, request, *args, **kwargs):
        # 前台通过urlencoding方式提交数据
        try:
            book_obj = models.Book.objects.create(**request.POST.dict())
            if book_obj:
                return JsonResponse({
                    'status': 0,
                    'msg': 'ok',
                    'results': {'title': book_obj.title, 'price': book_obj.price}
                }, json_dumps_params={'ensure_ascii': False})
        except:
            return JsonResponse({
                'status': 1,
                'msg': '参数有误',
            }, json_dumps_params={'ensure_ascii': False})

        return JsonResponse({
            'status': 2,
            'msg': '新增失败',
        }, json_dumps_params={'ensure_ascii': False})



# drf框架的封装风格
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.serializers import Serializer
from rest_framework.settings import APISettings
from rest_framework.filters import SearchFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import SimpleRateThrottle

# 总结:
# 1) drf 对原生request做了二次封装,request._request就是原生request
# 2) 原生request对象的属性和方法都可以被drf的request对象直接访问(兼容)
# 3) drf请求的所有url拼接参数均被解析到query_params中,所有数据包数据都被解析到data中
class Test(APIView):
    def get(self, request, *args, **kwargs):
        # url拼接的参数
        print(request._request.GET)  # 二次封装方式
        print(request.GET) # 兼容
        print(request.query_params) # 拓展

        return Response('drf get ok')

    def post(self, request, *args, **kwargs):
        # 所有请求方式携带的数据包
        print(request._request.POST)  # 二次封装方式
        print(request.POST)  # 兼容
        print(request.data)  # 拓展,兼容性最强,三种数据方式都可以

        print(request.query_params)

        return Response('drf post ok')

# 在setting.py中配置REST_FRAMEWORK,完成的是全局配置,所有接口统一处理
# 如果只有部分接口特殊化,可以完成 - 局部配置
from rest_framework.renderers import JSONRenderer
class Test2(APIView):
    renderer_classes = [JSONRenderer]
    def get(self, request, *args, **kwargs):
        return Response('drf get ok 2')

    def post(self, request, *args, **kwargs):
        return Response('drf post ok 2')

DRF Framework

installation
>: pip3 install djangorestframework
drf frame style rules package
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.serializers import Serializer
from rest_framework.settings import APISettings
from rest_framework.filters import SearchFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import SimpleRateThrottle

class Test(APIView):
    def get(self, request, *args, **kwargs):
        return Response('drf get ok')
drf request lifecycle
"""
1) 请求走的是APIView的as_view函数

2) 在APIView的as_view调用父类(django原生)的as_view,还禁用了 csrf 认证

3) 在父类的as_view中dispatch方法请求走的又是APIView的dispatch

4) 完成任务方法交给视图类的请求函数处理,得到请求的响应结果,返回给前台
"""

1.views.py视图文件中写一个类继承APIView,点击APIView

2.  renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
    parser_classes = api_settings.DEFAULT_PARSER_CLASSES
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
    throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
    content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
    metadata_class = api_settings.DEFAULT_METADATA_CLASS
    versioning_class = api_settings.DEFAULT_VERSIONING_CLASS
    看到以上这些所以的类属性都是可以在自定义类中来重写自定义renderer_class=[...]
    
3.这些类属性都是默认的,如果你没有重写这些类属性就默认找api_settings
views.py中导入from rest_framework.settings import APISettings, 点击APISettings进行查看,这个配置文件中说如果你设置rest_framework全局的名称空间,你需要到自己的项目中settings配置文件中进行自定义配置,否则就采用默认的

4.re_path(r'^test/$', views.Test.as_view()),访问路由的as_view(),走的是APIView中的as_view()

5.APIView的as_wiew()方法返回的是return csrf_exempt(view) 这是禁用csrf,也就是局部禁用csrf,继承APIView视图的类会禁用csrf认证

6.APIView中view=super().as_view(**initkwargs)  这里调用的super就是APIView父类

7.先不用点击APIView继承的父类,往上找发现是导包的View  from django.views.generic import View

8.这个View就是视图函数继承的View
from django.views import View 点击View查看,点击进去之后按pycharm的左上角定位到文件,发现就是views文件夹下没有View,所以走的是文件夹下__init__中的__all__=['View']
这个View是from django.views.genneric.base import View  
9.其实走的还是View中的return self.dispatch(request,*args,**kwargs),先走自定义类中Test中是否重写dispatch方法,没有就走APIView中的dispatch

10.APIView中根View不一样的地方就是有异常捕获,response = self.handle_exception(exc)这个是自己提供的

Requesting module: request Object

Source entrance

Method APIView dispatch class: request = self.initialize_request (request, * args, ** kwargs)

Source code analysis
"""
# 二次封装得到def的request对象
request = self.initialize_request(request, *args, **kwargs) 点进去

# 在rest_framework.request.Request实例化方法中
self._request = request  将原生request作为新request的_request属性

# 在rest_framework.request.Request的__getattr__方法中
try:
    return getattr(self._request, attr)  # 访问属性完全兼容原生request
except AttributeError:
    return self.__getattribute__(attr)
"""

1.入口是从APIView中的dispatch方法中看源码

2. request = self.initialize_request(request, *args, **kwargs)这是request的二次封装

3. try:
            self.initial(request, *args, **kwargs) #request对象处理完之后,请求之前执行的代码,这个通过了才可以请求,没有通过就是走response

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:#请求
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response
    
    
    
4.request = self.initialize_request(request, *args, **kwargs)点击initialize_request
parser_context = self.get_parser_context(request)将request传入进行解析数据

5.
#这个request是导入的from rest_framework.request import Request的类
这是在实例化
  return Request(
            request, #传入原生的request
            parsers=self.get_parsers(), #self代表视图函数中的自定义类的对象,没有重写的就到APIView中找打,解析数据
            authenticators=self.get_authenticators(),
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )

6.点击Request这个类,__init__先走断言,是否遵守了https协议,遵守了就到self._request = request#这是二次封装request,将原生reqeust作为drf request对象的_request

7.self.name这是会触发魔法方法__getattr__方法,所以找到Reuqest的__getattr__方法

8.
继承了APIView  request就不是原生django的,而是drf的request方法,request.属性就会触发(request.user)__getattr__
 def __getattr__(self, attr):
        """
        If an attribute does not exist on this instance, then we also attempt
        to proxy it to the underlying HttpRequest object.
        """
        try:
            return getattr(self._request, attr)  #而这里self._request是原生django的reqeust,在Request类实例化的时候进行赋值的,这里就是完全兼容了原功能,在此基础上再拓展新功能,先在这里面找,找不到去自己的self.__getattribute__(attr)中找
        except AttributeError:
            return self.__getattribute__(attr)

9.
views.py中的类
class Test(APIView):
    def get(self, request, *args, **kwargs):
        return Response('drf get ok')  #在这里打断点
然后postman发送GET http//127.0.0.1:8000/api/test/ 的请求数据
查看后台debug数据request展开,这里面找到下划线_request就是django原生的WSGIR协议的request
_request中可以找到GET,POST,META
在request中找不到GET,META,但是有data,POST,query_params
data是django,res_framework中三种方式提交数据包都会解析到这里来 比如PUT,POST
而GET请求的数据会解析到query_params里面

10.
#三种获取get请求数据的方法
class Test(APIView):
    def get(self, request, *args, **kwargs):
        # url拼接的参数
        print(request._request.GET)  # 二次封装方式
        print(request.GET) # 兼容
        print(request.query_params) # 拓展

        return Response('drf get ok')

11.
postman中发送post请求,使用form_data和json和urlencoded发送新增数据
    def post(self, request, *args, **kwargs):
        # 所有请求方式携带的数据包
        print(request._request.POST)  # 二次封装方式,这里只能获取到form_data和urlencoded的数据
        print(request.POST)  # 兼容,这里也只能获取搭配form_data和urlencoded的数据
        print(request.data)  # 拓展,兼容性最强,三种数据方式都可以,这里三种请求方式的数据都可以获取的到

        print(request.query_params)

        return Response('drf post ok')
Key summary
# 1) drf 对原生request做了二次封装,request._request就是原生request
# 2) 原生request对象的属性和方法都可以被drf的request对象直接访问(兼容)
# 3) drf请求的所有url拼接参数均被解析到query_params中,所有数据包数据都被解析到data中
class Test(APIView):
    def get(self, request, *args, **kwargs):
        # url拼接的参数
        print(request._request.GET)  # 二次封装方式
        print(request.GET) # 兼容
        print(request.query_params) # 拓展

        return Response('drf get ok')

    def post(self, request, *args, **kwargs):
        # 所有请求方式携带的数据包
        print(request._request.POST)  # 二次封装方式
        print(request.POST)  # 兼容
        print(request.data)  # 拓展,兼容性最强,三种数据方式都可以

        print(request.query_params)

        return Response('drf post ok')

Rendering module: Postman browser and request the results of rendering data in a different way

Source entrance

APIView类的dispatch方法中:self.response = self.finalize_response(request, response, *args, **kwargs)

Source code analysis
"""
self.response = self.finalize_response(request, response, *args, **kwargs)这里点击finalize_response进入

# 最后解析reponse对象数据
self.response = self.finalize_response(request, response, *args, **kwargs) 点进去

# 拿到运行的解析类的对象们
neg = self.perform_content_negotiation(request, force=True) 点进去

# 获得解析类对象
renderers = self.get_renderers() 点进去

# 从视图类中得到renderer_classes请求类,如何实例化一个个对象形参解析类对象列表
return [renderer() for renderer in self.renderer_classes]


# 重点:self.renderer_classes获取renderer_classes的顺序
#   自己视图类的类属性(局部配置) => 
#   APIView类的类属性设置 => 
#   自己配置文件的DEFAULT_RENDERER_CLASSES(全局配置) => 
#   drf配置文件的DEFAULT_RENDERER_CLASSES
"""
Global Configuration: All view class centrally, in settings.py project
REST_FRAMEWORK = {
    # drf提供的渲染类
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
}
Local configuration: one or a number of separate processing entity class, class attributes provide a corresponding class in view views.py
class Test(APIView):
    def get(self, request, *args, **kwargs):
        return Response('drf get ok')

    def post(self, request, *args, **kwargs):
        return Response('drf post ok')

# 在setting.py中配置REST_FRAMEWORK,完成的是全局配置,所有接口统一处理
# 如果只有部分接口特殊化,可以完成 - 局部配置
from rest_framework.renderers import JSONRenderer
class Test2(APIView):
    # 局部配置
    renderer_classes = [JSONRenderer]
    def get(self, request, *args, **kwargs):
        return Response('drf get ok 2')

    def post(self, request, *args, **kwargs):
        return Response('drf post ok 2')

Guess you like

Origin www.cnblogs.com/huangxuanya/p/11680325.html