table of Contents
A, DRF mounting frame
- DRF is a Django plugin, so you want to install Django in advance
- Run command
pip install djangorstframework
- To register app in settings.py use DRF:
INSTALLED_APPS = [..., 'rest_framework']
- CBV completed based on the interface specification to meet RSSTful
Second, the interface
(A) What is the interface
- Provides for submission: Interface request parameters of the request method , you can get access to it in response to feedback data of url links
- Four features
- url link: link url looks like a return data
- Request method: get, post, put, patch, delete
- Request Parameters: key-valu e data type or xml format json
- Response result: xml format data or json
(B) Interface Specification (RESTful)
(1) url links
- Using the https protocol: an interface station data are data before and after the operation, it is necessary to ensure the security of data
- API key: The interface used to manipulate data, and URL (operation page) are different, so the use of a specific keyword indicates
- Resource terminology: called data interface resources, reflected only in the url resource name, resource does not reflect the manner (https://api.baidu.com/get_books/), but rather to determine the operating mode for requesting resources the way
- General Resource Interface
- https://api.baidu.com/books/
- https://api.baidu.com/books/(pk)/
- Unconventional interfaces: a resource and not a particularly close or more than one resource
- https://api.baidu.com/books/login/
- https://api.baidu.com/books/place/search/
- General Resource Interface
- Multi-version coexistence: If there are multiple versions of a resource results in url link to use specific symbols compatible with multi-version coexistence
https://api.baidu.com/v1/books/
- https://api.baidu.com/v2/books/
? Restrictions: resource group operating in general as well as additional restrictions, such as sorting, limit testing, pagination, etc.
- https://api.baidu.com/v1/books/?ordering=price&limit=3/
(2) request method
- get request: Get single or multiple resource
https://api.baidu.com/books/: group search returns multiple result objects
- https://api.baidu.com/books/(pk)/: single check, returns a result object
post request: add single or multiple resource
- https://api.baidu.com/books: single whole and by increasing both the interface for a single or multiple return result objects
- put request: single or a plurality of resources to modify the overall
https://api.baidu.com/books/: modifying a plurality of integrally providing a plurality of dictionary data (the primary key to be included) in the array, the group completed change, return multiple result objects
- https://api.baidu.com/books/(pk)/: modify a single whole, provided a single data dictionary (embodied in the url primary key), a single change is completed, return a single result object
- patch request: single or multiple local modification of resource (common)
- Exactly the same way and put
- Different points: resource operation if five key key-value pair, provides PUT request dictionary must contain full, but the patch to provide a key dictionary contains 0 to 5 can be
- delete request: Delete single or multiple resources
- https://api.baidu.com/books/: Multi-delete, providing more resources to primary key data, no resources to return (usually custom information returned result: success or failure)
- https://api.baidu.com/books/(pk)/: single delete, do not need to provide additional data, no resources to return (usually custom information returned result: success or failure)
(3) a response result
- Network Status Code: response object to include in the network state (network status information and network status code bundle occurs, no extra setting)
1xx: Basic Information
2xx: Success
200: Basic
201: What's New Success
3xx: Redirection
4xx: Client Error
- 400: Bad Request
- 403: no permission request
- 404: requested resource does not exist
- 5xx: server error
- 500: Server Error
- Data status code (usually around the table agreed rules, specific information to be written in a clear interface document)
0: Success
1: Failed
2: No data
Data Status Code Information: General interpretation of the data is not only the status code, the result is a description of more of the developer to the front and rear ends of the reading
{ "status":0, 'msg':'ok' }
Data result (constants, arrays, dictionaries), if there are sub-resource (images, video, audio), returns connection resources url
{ "status":0, "msg":'ok', "results":[{ "name":"西游记", "img":"https://api.naidu.com/book/xyj.jpg" },{}] }
(C) Data Interface Documentation: YApi
- Where YApi is a large network of front-end technology center open-source visualization interface management platform
- Can build on any local or cloud server, complete the preparation of the interface at the time of project development background
- YApi test site: http://yapi.demo.qunar.com/
(D) Postman interface testing tool
- Postman is a free visual interface to debugging tools, and support a variety of operating platforms
- Postman Download: https://www.getpostman.com/downloads/
Three, DRF request lifecycle (CBV source)
Project starts, it will automatically execute as_view method, return to the calling function view (FBV is essentially)
View function returns the dispatch method of calling object
@classonlymethod def as_view(cls, **initkwargs): for key in initkwargs:…… # initkwargs没有进行赋值,该逻辑不会执行 def view(request, *args, **kwargs): # 请求来了完成响应的函数 self = cls(**initkwargs) # cls是我们自己写的类 MyLogin self是我们自己定义的类的对象 self.request = request # wsgi协议包装数据后的request self.args = args # 无名分组参数 self.kwargs = kwargs # 有名分组参数 return self.dispatch(request, *args, **kwargs) # view返回什么,用户就能看到什么 # 将请求来调用view的修改信息保存在view对象中 view.view_class = cls view.view_initkwargs = initkwargs # 看源码的时候一定要注意在查找属性和方法的时候先从对象自身找,再去类中查找,再去父类查找 return view # 返回请求调用的函数地址,进行路由绑定
dispatch function using the reflection method of obtaining a mode request to call the corresponding methods
def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. # 判断当前请求方式在不在默认的八个方法内 # 1.先以GET请求为例 if request.method.lower() in self.http_method_names: # 利用反射去我们自己定义类的对象中查找get属性或者是方法 getattr(obj,'get') # handler = get方法 handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) # 调用get方法