Rest-framework Parser

Source: Internet
Author: User
Tags parse error

Parser 1.json Parser

Send a POST request in JSON format.
Spool print: Request_data---> {'title' ' Beijing folding '}request. POST---> <querydict: {}>
2.urlencode Parser

Request_data---> <querydict: {'title': ['Beijing'],' Price': ['122']}>request. POST---> <querydict: {'title': ['Beijing'],' Price': ['122']}>

Rest-framework default support for 3 kinds of parsers, json,form, file upload. The Django native only supports parsing of the form and does not support JSON parsing.

Source:

JSON Parser class:

classJsonparser (baseparser):"""parses json-serialized data. """Media_type='Application/json'Renderer_class=renderers. Jsonrenderer Strict=api_settings. Strict_jsondefParse (self, stream, Media_type=none, parser_context=None):"""parses the incoming bytestream as JSON and returns the resulting data. """Parser_context= Parser_contextor{} encoding= Parser_context.get ('encoding', settings. Default_charset)Try: Decoded_stream=Codecs.getreader (encoding) (stream) Parse_constant= Json.strict_constantifSelf.strictElseNonereturnJson.load (Decoded_stream, parse_constant=parse_constant)exceptValueError as exc:RaiseParseError ('JSON Parse Error-%s'% Six.text_type (exc))

Form Parser class:

classFormparser (baseparser):"""Parser for form data. """Media_type='application/x-www-form-urlencoded'    defParse (self, stream, Media_type=none, parser_context=None):"""parses the incoming bytestream as a URL encoded form, and returns the resulting querydict. """Parser_context= Parser_contextor{} encoding= Parser_context.get ('encoding', settings. Default_charset) Data= Querydict (Stream.read (), encoding=encoding)returnData

File Upload class:

classMultipartparser (baseparser):"""Parser for multipart form data, which may include file data. """Media_type='Multipart/form-data'    defParse (self, stream, Media_type=none, parser_context=None):"""parses the incoming bytestream as a multipart encoded form, and returns a Dataandfiles object.        '. Data ' is a ' querydict ' containing all the form parameters.        '. Files ' would be a ' querydict ' containing all the form files. """Parser_context= Parser_contextor{} request= parser_context['Request'] Encoding= Parser_context.get ('encoding', settings. Default_charset) Meta=request. Meta.copy () meta['Content_Type'] =media_type upload_handlers=request.upload_handlersTry: Parser=djangomultipartparser (meta, stream, upload_handlers, encoding) data, files=Parser.parse ()returndataandfiles (data, files)exceptMultipartparsererror as exc:RaiseParseError ('Multipart Form Parse error-%s'% Six.text_type (exc))
URL control

1. Because each URL needs to write the following 2 lines, resulting in code redundancy.

# URL (r ' authors/$ ', views. Authormodelview.as_view ({"Get": "List", "POST": "Create"}), name= "authors"),#  url (r ' authors/(? p<pk>\d+)/$ ', views. Authormodelview.as_view ({"Get": "Retrieve", "Put": "Update", "delete": "Destroy"}), Name= "Authordetail"),

2. Using Rest-framework to provide:

 from Import Url,include  from Import  views  from Import routersrouters=routers. Defaultrouter () routers.register ("authors", views. Authormodelview)

Add this sentence to the URL:

URL (r', include (Routers.urls)),

After each table, register it, the prefix of the preceding URL, followed by the corresponding view class.

Page out

Rest-framework Parser

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: info-contact@alibabacloud.com 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.