drf framework - Basic

drf framework

Importing

  • http protocol

    http protocol is based on the application layer protocol

    Upon request, the request need to have the first line, the first request, request body

    Features: No No connection, and are the first client initiates the request, the server then responds

  • wsgi agreement

    Mainly specifies how data is parsed, and the like to get http request to the request analysis package which

    When the function returns the view, then the data is packaged into the format required by the http protocol reception spread

What is the interface

The client needs returned, route matching, call the appropriate interface, and an interface performing data is complete, be returned in a desired format.

  • Interface has a specific url link
  • Manner corresponding request: get, post, put, patch, delete
  • Reception parameter request
  • Last response

restful Interface Specification

  1. Security protocol commonly used, because the interface is operating on data

  2. To reflect the keywords in the url of the interface api, such as:

    http://api.baidu.comorhttp://www.baidu.com/api

  3. When data interface called the resource, to request data reception using the plural resource

    http://api.baidu.com/books/orhttp://www.baidu.com/api/books

  4. Link interface operating in the way of resources can not appear, usually to determine the operating mode of the resource request by way

    Five interfaces:

    • get: Get all
    • get: get a
    • post: Add a
    • put | patch: Modify the whole | amend section
    • delete: delete a
  5. When there are multiple versions of the resource data, the interface to do version control

    http://api.baidu.com/books/v1/

  6. Resource constraints response: screening, sorting ......

    http://api.baidu.com/books/?publish=1&ordering=-price&limit=3

  7. Data corresponding status code, status code similar to the network, the convention is 0

    {‘status’: 0 | 1 | 2}

    - SUCCESS (0, "Query successful")
    - the NODATA (1, "incorrect, no data, display basic information")
    - FEAILED (2, "Query failed")

  8. The results described response information needed

    {'status': 0, 'msg': 'success'}

  9. The results of the response

    • get all: return all resources
    • get a: Returns a resource
    • Add a post: Return additional resources
    • put | patch Review: returns a resource modification
    • delete: without any return

Note: The need to interface documentation the front desk told delivery of essential and optional parameters, and data content structure returned

Django implement native interfaces

Create a new django project, create a default app, called api

# 主路由urls.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 = [
    # as_view() 本质拿到 view函数地址,
    # view内部通过dispatch分发请求给具体的(get|post|delete)方法处理请求
    # 处理完后的响应结果会一层层返回
    url(r'^books/$', views.BookView.as_view()),
    url(r'^books/(?P<pk>.*)/$', views.BookView.as_view()),
]

# 模型层 api/models.py

from django.db import models
class Book(models.Model):
    name = 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 self.name
# 模型层创建完成之后,完成数据库的迁移
# python manage.py makemigrations
# python manage.py migrate
    
# 视图层 api/views
from django.views import View
from django.http import JsonResponse
from . import models
class BookView(View):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:  # 通过是否有主键决定获取单个或是全部资源
            book_dic_list = models.Book.objects.filter(pk=pk).values('name', 'price')
            if not book_dic_list:
                return JsonResponse({
                    'status': 2,
                    'msg': 'pk值有误',
                    'results': {}
                })
            return JsonResponse({
                'status': 0,
                'msg': 'ok',
                'results': book_dic_list[0]
            })

        book_dic_list = models.Book.objects.all().values('name', 'price')
        if not book_dic_list:
            return JsonResponse({
                'status': 2,
                'msg': '无数据',
                'results': {}
            })
        return JsonResponse({
            'status': 0,
            'msg': 'ok',
            'results': list(book_dic_list)
        })

drf framework

  • Installation :

    pip install djangorestframework

  • Configuration :

    # 注册drf app
    # settings.py
    NSTALLED_APPS = [
        # ...
        'rest_framework',
    ]
  • Features :

    # 具体功能在具体模块下
    from rest_framework.request import Request
    from rest_framework.response import Response
    from rest_framework.exceptions import APIException
    from rest_framework.filters import OrderingFilter
    from rest_framework.views import APIView
    from rest_framework.pagination import PageNumberPagination
    from rest_framework.settings import APISettings
    
    
    # 自定义drf配置 - 在自己的settings.py
    REST_FRAMEWORK = {
        # 自定义修改drf的配置们
    }

Django CBV and drf CBV contrast

  • Django CBV

    1. Inherit the Viewview class
    2. By as_view()acquiring view function address
    3. After the request, calling view function, internal call dispatch function to complete the requested distribution
    4. request dispatch function mapped to the method of the view class of the same name, the request processing is completed, to give the corresponding,
    5. Finally, the respective layers of a return result
  • drf CBV

    1. Inherited APIViewclass
    2. By as_view()(继承自django的as_view)acquiring view function address, but in view of the function of local disabled csrf certification
    3. Request to view the function call, internal call ( APIView类的) function to complete the request dispatch distribution
    4. dispatch function of the second package Request , for the three authentication , the request is then mapped to the method of the view class of the same name, the request processing is completed, to give the corresponding, again to do rendering processing corresponding
    5. Finally, the respective layers of a return result

In response rendering module

Data is returned in the form of: json and browser interfaces page

Analysis :

# 入口: APIView类的dispatch函数
self.response = self.finalize_response(request, response, *args, **kwargs)
--> neg = self.perform_content_negotiation(request, force=True)
--> renderers = self.get_renderers()
--> self.renderer_classes
--> APISetting:DEFAULT_RENDERER_CLASSES

Local Configuration

from rest_framework.views import APIView
from rest_framework.response import Response

from rest_framework.renderers import JSONRenderer
from rest_framework.renderers import BrowsableAPIRenderer
class UserAPIView(APIView):
    # 局部配置:只有该视图类起作用
    renderer_classes = [JSONRenderer]  # 只提供JSON数据渲染
    pass

Global Configuration

# drf配置
REST_FRAMEWORK = {
    # 响应的渲染模块
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
}

Request data parsing module

Data Frontend mode request parsing: JSON, form-Data, URLEncoding

Analysis :

# 入口:APIView类的dispatch函数
request = self.initialize_request(request, *args, **kwargs)
--> parsers=self.get_parsers()
--> self.parser_classes
--> APISetting:DEFAULT_PARSER_CLASSES

Local Configuration

from rest_framework.views import APIView
from rest_framework.response import Response

from rest_framework.parsers import JSONParser
from rest_framework.parsers import FormParser
from rest_framework.parsers import MultiPartParser
class UserAPIView(APIView):
    # 局部配置:只有该视图类起作用
    parser_classes = [JSONParser]  # 只提供JSON解析
    pass

Global Configuration

# drf配置
REST_FRAMEWORK = {
    # 请求数据解析模块
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',  # 'application/json'
        'rest_framework.parsers.FormParser',  # 'application/x-www-form-urlencoded'
        'rest_framework.parsers.MultiPartParser'  # multipart/form-data
    ],
}

The analysis of the positional data request

  1. If a packet is to resolve all the request.data
  2. If the url /?参数is resolved in the request.query_params

Response module

# 响应可以设置响应数据、响应网络状态码、响应头、响应数据类型等
data = {
    'status': 0,
    'msg': 'get ok',
    'results': [],
    'token': '123.12321.231'
}
return Response(
    data=data,
    status=status.HTTP_200_OK,
    headers={'Token': '123as.masd21.asd213sd'},
    content_type='application/json'  # 默认就是application/json
)

Guess you like

Origin www.cnblogs.com/Hades123/p/11455876.html