Analysis module
Why To configure the analysis module
(1), drf to us by the various classes packet parsing data analysis method.
(2), we can control the format of the data table to resolve those submitted by configuring the front desk, data that does not resolve.
(3), the global configuration is for a view class, for the specified local configuration is used to view, so that we can parse the data in accordance with selectivity.
Source entrance
# DISP method APIView class Request = self.initialize_request (Request, * args, ** kwargs) # point into # Get resolve class parsers = self..get_parsers () # point into # To the class attribute (partial configuration) or profile (global configuration) take parser_classes return [parser() for parser in self.parser_classes]
Global Configuration: project settings.py file
= REST_FRAMEWORK { # global parser class configuration ' DEFAULT_PARSER_CLASSES ' : [ ' rest_framework.parsers.JSONParser ' , # JSON packet ' rest_framework.parsers.FormParser ' , # URLEncoding packet ' rest_framework.parsers.MultiPartParser ' # form packet-DATE ], }
Local configuration: application specific view class views.py
from rest_framwork.parsers import JSONParser class Book (APIView):
# locally resolved class configuration as long as JSON; type of packet to be parsed parser_classes = [JASONParser] Pass
Acquired parsed from source global configuration
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.parsers import JSONParser from . Import Models, serializers class Book (APIView): # locally resolved class configuration parser_classes = [JSONParser] DEF GET (Self, Request, * args, ** kwargs): pk = kwargs.get('pk') if pk: book_obj = models.Book.objects.get(pk=pk) return Response({ 'status': 0, 'msg': 'ok', 'results': { 'title': book_obj.title, 'price': book_obj.price } }) return Response('get ok') DEF POST (Self, Request, * args, ** kwargs): # URL splicing parameters: parameter passing only one way is spliced parameter Print (request.query_params) # packet parameters: Inheritance of three ways, form-data, urlencoding , JSON Print (request.data) return the Response ( ' POST OK ' )
Abnormal module
Why custom exception module
(1), through APIView all exceptions generated drf view class, are an exception processing scheme
(2), drf provided by default exception handling scheme (ref_framework.views.exception_handler), but the limited processing range
(3), provide treatment options drf there are two, the return process anomalies, not the process returns None (subsequent server is throwing an exception to the foreground)
(4), custom exception aim is to resolve exceptions drf no treatment, let the front desk to get a reasonable return exception information, background information on exceptions record
Source code analysis
# Exception Module: dispatch method APIView class Response = self.handle_exception (EXC) # point into # Obtain a handle to handle exceptions (method) # layers look at the source code, taking the configuration file, get a rest_framework.views of exception_handler # custom: to write directly exception_handler function in their own profile configuration EXCEPTION_HANDLER point to their own = exception_handler self.get_exception_handler () # Result exception handling # custom exception definitions is to provide exception_handler exception handler, the purpose of the treatment is to make the response must be a value response = exception_handler (exc, context)
How to use: customize how exception_handler writing implement body function
# Modify their profile setting.py REST_FRAMEWORK = { # Global configuration module abnormal ' EXCEPTION_HANDLER ' : ' api.exception.exception_handler ' , }
Excep.py a new file, for abnormality determination processing
# 1) The first exception handling to rest_framework.views exception_handler to deal with # 2 results) judgment processing (return value) response, there is value represents drf has been processed, the processing needs its own behalf None # Custom exception handling file exception, writing exception_handler function in the file
from rest_framework.views Import exception_handler AS drf_exception_handler from rest_framework.views Import the Response from rest_framework Import Status DEF exception_handler (EXC, context): # DRF foundation process of exception_handler Response = drf_exception_handler (EXC, context) # empty, custom secondary treatment IF Response IS None: # Print (EXC) # Print (context) Print ( ' % S -% S -% S ' % (context [ ' View'], context['request'].method, exc)) return Response({ 'detail': '服务器错误' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True) return response
Response module
Response class constructor: ref_framework.response.Response
def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None): """ : Param data: response data : Param status: http response status code : Param template_name: drf can render the page, rendering the page template address (do not understand) : Param headers: response header : Param exception: if the abnormal : Param content_type: the data format of the response (usually not treated, with a response header, and the default is json) """ pass
Use: Conventional Example Response Object
# Status interpretation module is a bunch of numbers of network status code
from rest_framework Import Status is explained pile digital network module status code
# generally only need to return data, status headers have default values, and
return the Response (data Data = {} , status = status.HTTP_200_OK, headers = {} disposed response header)
Serialization assembly
Knowledge Point: Seralizer (partial bottom), ModelSerialier (focus), ListModelSerializer (auxiliary group to change)
Seralizer
Serialization preparation:
The model layer: models.py
class User(models.Model): SEX_CHOICES = [ [0, ' M ' ], [ 1, ' F ' ], ] name = models.CharField(max_length=64) pwd = models.CharField(max_length=32) phone = models.CharField(max_length=11, null=True, default=None) sex = models.IntegerField(choices=SEX_CHOICES, default=0) icon = models.ImageField(upload_to='icon', default='icon/default.jpg') class Meta: db_table = 'old_boy_user' verbose_name = '用户' verbose_name_plural = verbose_name def __str__(self): return '%s' % self.name
Backstage management: admin.py
from django.contrib import admin from . import models admin.site.register(models.User)
Configuration layer: settings.py
# 注册rest_framework INSTALLED_APPS = [ # ... 'rest_framework', ] # Configuration database DATABASES = { ' default ' : { ' ENGINE ' : ' django.db.backends.mysql ' , ' NAME ' : ' day70 ' , ' the USER ' : ' the root ' , ' PASSWORD ' : ' 123 ' } } # Media Resource MEDIA_URL = ' / Media / ' # late advanced classes and serialized view class, uses the configuration of MEDIA_ROOT it the os.path.join = (base_dir, ' Media ' ) # Media Resource route
International configurations, Chinese display
The main routes: the next project urls.py
urlpatterns = [ # ... url(r'^api/', include('api.urls')), url(r'^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}), ]
Sub Routing: Application urls.py
urlpatterns = [ url(r'^users/$', views.User.as_view()), url(r'^users/(?P<pk>.*)/$', views.User.as_view()), ]
Some important source of screenshots
Module source code analysis
Exception Handling Code section
Use serialization