Introduction 72-DRF plug / interface concept

A, drf framework Introduction

1. drf installation

1, drf django is a plug frame, the first mounting django;

2, the installation command:pip3 install djangorestframework

3, the use drf, to be registered in the settings

2. drf advantage

Rest API interfaces may improve the development efficiency of separation of the rear end of the previous development.

Second, the interface

Concepts Interface

What is the interface: specifies the url link to submit a request mode, it can get feedback data access response. That is the media front and back office information exchange.

Composition interface: url link request method + + + response data request parameters

2. Document Interface

A qualified interface should have a copy of the corresponding document that can help users use the interface better and faster understanding of the interfaces to be developed.

The preparation of the document is very simple, just four components of the interface can be translated into a form of documentation.

Including but not limited to interface path, the request mode, the request parameters and the response data format.

3. Interface Specification (RESTful)

3.1 url link specification

  1. Operating data interfaces are front and back, so the need to ensure the security of data, thus:

    • Using https protocol
  2. Interface is used to manipulate the data, there are differences with the URL (operating page), it indicates that the interface on a specific keyword:

    • api key
    - https://api.baidu.com
    - https://www.baidu.com/api
  3. Data interface called resource , reflected only in the url Resource Name (noun), the operation mode is not reflected in the resource verb (i.e., without get_bookthis naming)

    • General Resource Interface (only with the noun)
    - https://api.baidu.com/books/
    - https://api.baidu.com/books/(pk)/
    • Unconventional interfaces - and some resources are not particularly close or more than one resource (available verb)
    - https://api.baidu.com/login/
    - https://api.baidu.com/place/search/    
  4. If there are multiple versions of a resource results in url link to use specific symbols compatible with multi-version coexistence

    • v1|v2
    - https://api.baidu.com/v1/books/
    - https://api.baidu.com/v2/books/        
  5. Resource group operations, generally there are additional restrictions, such as sorting, limit testing, pagination, etc.

    • ? + Restrictions
    https://api.baidu.com/v1/books/?ordering=-price&limit=3

3.2 specification request method

Five requests ways:

  1. get: Gets a single or multiple resources

    - https://api.baidu.com/books/
    群查,返回多个结果对象
    
    - https://api.baidu.com/books/(pk)/
    单查,返回单个结果对象
  2. post: Add single or multiple resources

    - https://api.baidu.com/books/
    单增,提交单个数据字典,完成单增,返回单个结果对象
    群增,提供多个数据字典的数组,完成群增,返回多个结果对象
  3. put: single or a plurality of resources to modify the overall

    - https://api.baidu.com/books/
    整体修改多个,提供多个数据字典的数组(数据字典中要包含主键),完成群改,返回多个结果对象
    
    - https://api.baidu.com/books/(pk)/
    整体修改单个,提供单个数据字典(主键在url中体现),完成单改,返回单个结果对象
  4. patch: a plurality of local resources or modify individual

    方式与put完全相同,不同的是:操作的资源如果有5个key-value键值对,put请求提供的字典必须全包含,但是patch提供的字典包含的键值对0~5个都可以,就是不必包含所有可以修改的数据。
  5. delete: delete a single or multiple resources

    - https://api.baidu.com/books/
    多删,提供多个资源主键数据,完成群删,不做任何资源返回(一般我们会返回结果信息:成功|失败)
    
    - https://api.baidu.com/books/(pk)/
    单删,不需要提供额外数据,完成单删,不做任何资源返回(一般我们会返回结果信息:成功|失败)

Response result Specification 3.3

  1. Network status code (network status information and network status code bundled appears, do additional settings):
    • 1xx: Basic Information
    • 2xx: Success
      • 200 Basic
      • 201 new success
    • 3xx: Redirection
    • 4xx: Client Error
      • 400 Bad Request
      • 403 no permission request
      • 404 the requested resource does not exist
    • 5xx: server error
      • 500 Server Error
  2. Data status code (usually foreground and agreed rule):
    • 0: Success
    • 1: Failed - 1xx: specific failure information (to be expressly written interface document)
    • 2: No data - 2xx: No specific data (to be expressly written interface document)
  3. Data status information (general interpretation of the data is not only the status code, the result is a description of more, to the front of the developer reading):

  4. Data result (constants, arrays, dictionaries), if there are sub-resource (images, audio, video), returns a resource link:

    {
        "status": 0,
        "msg": 'ok',
        "results": [{
            "name": "西游记",
            "img": "https://api.baidu.com/media/book/abc.png"
        }]
    }

4. Interface Specification wording

A resource corresponding to a ten Interface

# urls.py
from django.conf.urls import url

from . import views
urlpatterns = [
    # http://127.0.0.1:8000/api/books/
    # http://127.0.0.1:8000/api/books/(pk)/
    url(r'^books/$', views.BookView.as_view()),
    url(r'^books/(?P<pk>\d+)/$', views.BookView.as_view())
]
# views.py
from django.http import JsonResponse
from django.views import View
from . import models
# 一个视图类可以保护常规五个请求方法:get|post|put|patch|delete
# 五个请求方法处理十个资源操作的逻辑:单群查|单群增|单群整体改|单群局部改|单群删

class BookView(View):

    def _single_get(self, pk):
        book_dic = models.Book.objects.filter(pk=pk).values('name', 'price').first()
        if not book_dic:
            return JsonResponse({
                'status': 1,
                'msg': '单查 资源不存在',
            })
        return JsonResponse({
            'status': 0,
            'msg': '单查 ok',
            'results': book_dic
        })
    def _many_get(self):
        book_query = models.Book.objects.values('name', 'price')
        book_list = list(book_query)
        return JsonResponse({
            'status': 0,
            'msg': '群查 ok',
            'results': book_list
        })

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:  # 单查
            return self._single_get(pk)
        else:  # 群查
            return self._many_get()

    def post(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'post ok'
        })

    def put(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'put ok'
        })

    def patch(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'patch ok'
        })

    def delete(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'delete ok'
        })

Guess you like

Origin www.cnblogs.com/bowendown/p/12087987.html