rest-framework解析器

來源:互聯網
上載者:User

標籤: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,includefrom app01 import viewsfrom rest_framework import routersrouters=routers.DefaultRouter()routers.register("authors",views.AuthorModelView)

url中需要加這一句即可:

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

以後每一個表,註冊一下即可,前面的是url的首碼,後面是對應的視圖類。

分頁

rest-framework解析器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.