码迷,mamicode.com
首页 > 其他好文 > 详细

rest-framework解析器

时间:2018-10-07 15:29:17      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:style   put   work   center   let   constant   post请求   一个   erer   

解析器

1.json解析器

技术分享图片

发一个json格式的post请求。
后台打印: request_data
---> {title: 北京折叠} request.POST---> <QueryDict: {}>

2.urlencode解析器

技术分享图片

request_data---> <QueryDict: {title: [北京], price: [122]}>
request.POST---> <QueryDict: {title: [北京], price: [122]}>

rest-framework默认支持的有3种解析器,json,form,文件上传。而Django原生只支持form的解析,不支持json的解析。

源码:

JSON解析器类:

class JSONParser(BaseParser):
    """
    Parses JSON-serialized data.
    """
    media_type = application/json
    renderer_class = renderers.JSONRenderer
    strict = api_settings.STRICT_JSON

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as JSON and returns the resulting data.
        """
        parser_context = parser_context or {}
        encoding = parser_context.get(encoding, settings.DEFAULT_CHARSET)

        try:
            decoded_stream = codecs.getreader(encoding)(stream)
            parse_constant = json.strict_constant if self.strict else None
            return json.load(decoded_stream, parse_constant=parse_constant)
        except ValueError as exc:
            raise ParseError(JSON parse error - %s % six.text_type(exc))

form解析器类:

class FormParser(BaseParser):
    """
    Parser for form data.
    """
    media_type = application/x-www-form-urlencoded

    def parse(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_context or {}
        encoding = parser_context.get(encoding, settings.DEFAULT_CHARSET)
        data = QueryDict(stream.read(), encoding=encoding)
        return data
        

文件上传类:

class MultiPartParser(BaseParser):
    """
    Parser for multipart form data, which may include file data.
    """
    media_type = multipart/form-data

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as a multipart encoded form,
        and returns a DataAndFiles object.

        `.data` will be a `QueryDict` containing all the form parameters.
        `.files` will be a `QueryDict` containing all the form files.
        """
        parser_context = parser_context or {}
        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_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
            data, files = parser.parse()
            return DataAndFiles(data, files)
        except MultiPartParserError as exc:
            raise ParseError(Multipart form parse error - %s % six.text_type(exc))

 URL控制

1.因为每次url都需要写下面的2条线,导致代码冗余。

 # 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.使用rest-framework提供的:

from django.conf.urls import url,include
from app01 import views

from rest_framework import routers
routers=routers.DefaultRouter()
routers.register("authors",views.AuthorModelView)

url中需要加这一句即可:

url(r‘‘,include(routers.urls)),

以后每一个表,注册一下即可,前面的是url的前缀,后面是对应的视图类。

分页

rest-framework解析器

标签:style   put   work   center   let   constant   post请求   一个   erer   

原文地址:https://www.cnblogs.com/geogre123/p/9750057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!