10.15 summary

Analysis module

Why To configure the analysis module

1.drf to us by a variety of analytical class to parse the data packet mode

2. We can control the configuration of the data submitted by the front desk which form the background of the resolution, which does not parse the data

Configuring global is a view for each class for the specified local configuration is to view, so that they can be selectively parse data in accordance with configuration rules

 

Source entrance

# Dispatch method APIView class 
Request = self.initialize_request (Request, * args, ** kwargs)   # point into 

# acquiring and analyzing based 
parsers self.get_parsers = (),   # point into 

# to the class attribute (partial configuration) or configuration file (global configuration) take parser_classes 
return [Parser () for Parser in self.parser_classes]

 

Global Configuration: Project settings.py

= 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-Data packets 
    ], 
}

 

Local configuration: application specific view class views.py

from rest_framework.parsers Import JSONParser
 class Book (APIView):
     # locally resolved class configuration as long as json type of packet is parsed to 
    parser_classes = [JSONParser]
     Pass

 

 

Abnormal module

Why custom exception module

1. After all exceptions APIView view class drf produced, are an exception processing scheme

2.drf provided by default exception handling scheme (rest_framework.views.exception_handler), but the limited processing range

Two schemes 3.drf treatment provided by processing the return anomaly, not the process returns None (subsequent server is throwing an exception to the foreground)

4. Since the purpose of defining an exception is not handled resolve exceptions drf, so 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 

# acquired exception handler process (method) 
# layers look source, taking the configuration file, get the rest_framework.views the exception_handler 
# custom: to write directly exception_handler function in their own profile configuration EXCEPTION_HANDLER point = self.get_exception_handler own exception_handler () 

# result exception handling 
# custom exception definitions is to provide exception_handler exception handler, the aim is to make treatment response must have a value 
response = exception_handler (exc, contexxt)

 

How to use: customize how exception_handler writing implement body function

# Modify their own profile the settings.py 
REST_FRAMEWORK = {
     # Global configuration module abnormal 
    ' EXCEPTION_HANDLER ' : ' api.exception.exception_handler ' , 
} 


# 1. First rest_framework.views to the exception handling process to exception_handler 
# 2. Analyzing result of the processing (return value) response, there is value represents drf been processed, on behalf None need to deal with their own 

# 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 [ ' Request ' ] .method, EXC))
         return the Response ({
             ' Detail ' : ' server error ' 
        }, Status = status.HTTP_500_INTERNAL_SERVER_ERROR, Exception =True)
    return response

 

Response module

Response class constructor: rest_framework.response.Response

DEF  the __init__ (Self, Data = None, Status = None, 
                        template_name = None, headers = None, 
                        Exception = False, the content_type = None:
         "" " 
            : param Data: Response Data 
            : param status: http response status codes 
            : param template_name: drf can also render the page, rendering the page template address (do not understand) 
            : param headers: response header 
            : param exception: if the anomaly 
            : param content_type: data format of the response (usually without treatment, the response header brought, and the default is json) 
        "" " 
        Pass

 

Use: Conventional Example Response Object

# Status module is to explain a bunch of digital network status codes

from rest_framework import status interpretation module is a bunch of numbers of network status code

# Only need to return data under normal circumstances, status and headers have default values

return Response (data = {data}, status = status.HTTP_200_ok, headers = { } disposed response header )

 

Serialization assembly

Knowledge Point: Serializer (partial bottom), ModelSerializer (focus), ListModelSerializer (auxiliary group to change)

 

Serializer

Serialization preparation:

- Model layer: models.py

class User(models.Model):
    SEX_CHOICES = [
        [0, ''],
        [1, ''],
    ]
    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

 

- Background Management: admin.py

from django.contrib import admin
from . import models

admin.site.register(modesl.User)

 

Guess you like

Origin www.cnblogs.com/TZZ1995/p/11681406.html