Python-django REST Framework Framework Parser

Source: Internet
Author: User
Tags parse error

1. Parser: Parse the requested data-the request body for parsing. The parser is not called when you do not take the request body data.

classUsersview (apiview):defGet (self,request,*args,**Kwargs):returnResponse ('...')    defPost (self,request,*args,**Kwargs):## Application/json        #print (request._request.body) # B "xxxxx" Decode () Json.loads        #Print (request._request. POST) # None        #when the data format of the POST request is Application/json, Request._request.body has a value, and request._request. Post does not have a value        #we're going to get the data through Decode + json.loads.                ## Www-form-url-encode        #print (request._request.body)        #Print (request._request. POST)        #when the data format of the POST request is Www-form-url-encode, Request._request.body and Request._request. Post has a value                        #and when we use the rest framework is often sent in the JSON format of data, then we have to so much trouble to convert, the answer is certainly not        #you can set parser_classes                 fromRest_framework.parsersImportJsonparser,formparserclassUsersview (Apiview): Parser_classes=[Jsonparser,formparser] #表示服务端可以解析的数据格式的种类.
#如果客户端的Content-type value and Application/json match: jsonparser processing data
#如果客户端的Content-type value and application/x-www-form-urlencoded match: formparser processing data
defGet (self,request,*args,**Kwargs):returnResponse ('...') defPost (self,request,*args,**Kwargs) is processing the converted data {' name ': ' xxx ', ' age ': ' Print( print(request. FILES)
          Print(request. POST)
return Response (' ... ')

     # Global use: Configuration files are generally used by default with global configuration
Rest_framework = {
' Default_parser_classes ': [
' Rest_framework.parsers.JSONParser ',
' Rest_framework.parsers.FormParser ',

2. print( source code

classRequest (object): @propertydefdata (self):if  not_hasattr (Self,'_full_data'):
#调用_load_data_and_files Method Self._load_data_and_files ()returnSelf._full_datadef_load_data_and_files (self):if not_hasattr (Self,'_data'):
#调用_parse method Self._data, Self._files=Self._parse ()def_parse (self):
#调用 the Select_parser method of the Defaultcontentnegotiation class, see below Parser= Self.negotiator.select_parser (self, self.parsers)#self.parser = configured object list for resolved classes at the time of package request #self.negotiator = self._default_negotiator () = Api_settings. Default_content_negotiation_class () if notparser:#if the return none description does not match, throws an exception Raiseexceptions. Unsupportedmediatype (media_type)Try: #match succeeds, the corresponding parse class object calls the Parse methodparsed =Parser.parse (Stream, Media_type, Self.parser_context)classdefaultcontentnegotiation (basecontentnegotiation):defSelect_parser (self, request, parsers): forParserinchparsers:#determines whether the object of the resolved class and the content_type of the request match ifmedia_type_matches (Parser.media_type, request.content_type):returnParserreturnNone Take Jsonparser for exampleclassJsonparser (baseparser): Media_type='Application/json'Renderer_class=renderers. Jsonrenderer Strict=api_settings. Strict_jsondefParse (self, stream, Media_type=none, parser_context=None):Try: #和我们自己处理是一个原理#First decodeDecoded_stream =Codecs.getreader (encoding) (stream) Parse_constant= Json.strict_constantifSelf.strictElseNone#again load returnJson.load (Decoded_stream, parse_constant=parse_constant)exceptValueError as exc:RaiseParseError ('JSON Parse Error-%s'% Six.text_type (exc))

Python-django REST Framework Framework Parser

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.