zoukankan      html  css  js  c++  java
  • django rest framework之解析器的源码流程剖析

    在初始化Request的时候:

     1     def initialize_request(self, request, *args, **kwargs):
     2         """
     3         Returns the initial request object.
     4         """
     5         parser_context = self.get_parser_context(request)
     6 
     7         return Request(
     8             request,
     9             parsers=self.get_parsers(), #添加解析器
    10             authenticators=self.get_authenticators(),
    11             negotiator=self.get_content_negotiator(),
    12             parser_context=parser_context
    13         )

    内置的json解析器可以在视图类中添加:如parser_classes = [JSONParser,]

     1 class JSONParser(BaseParser):
     2     """
     3     Parses JSON-serialized data.
     4     """
     5     media_type = 'application/json'
     6     renderer_class = renderers.JSONRenderer
     7     strict = api_settings.STRICT_JSON
     8 
     9     def parse(self, stream, media_type=None, parser_context=None):
    10         """
    11         Parses the incoming bytestream as JSON and returns the resulting data.
    12         """
    13         parser_context = parser_context or {}
    14         encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
    15 
    16         try:
    17             decoded_stream = codecs.getreader(encoding)(stream)
    18             parse_constant = json.strict_constant if self.strict else None
    19             return json.load(decoded_stream, parse_constant=parse_constant)
    20         except ValueError as exc:
    21             raise ParseError('JSON parse error - %s' % six.text_type(exc))
  • 相关阅读:
    第一天
    python自测——其他内容
    python自测——正则表达式
    python自测——高级特性
    人机对战石头剪刀布代码
    [Usaco2004 Nov]Til the Cows Come Home 带奶牛回家
    Dijkstra概念
    洛谷p1339--热浪
    0-1背包问题变形------------cow exhibition
    [Poi2005]Piggy Banks小猪存钱罐
  • 原文地址:https://www.cnblogs.com/arrow-kejin/p/9992934.html
Copyright © 2011-2022 走看看