django rest framework - 数据解析

来源:互联网 发布:映客刷人气软件 购买 编辑:程序博客网 时间:2024/06/03 18:37

摘要 parser.py是rest-framework的数据解析模块, 它能够解析大多数的数据格式(json,xml,yaml)

?
1
<br>

所有数据解析的类都是BaseParser的子类。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class BaseParser(object):
    """
    All parsers should extend `BaseParser`, specifying a `media_type`
    attribute, and overriding the `.parse()` method.
    """
 
    media_type = None
 
    def parse(self, stream, media_type=None, parser_context=None):
        """
        Given a stream to read from, return the parsed representation.
        Should return parsed data, or a `DataAndFiles` object consisting of the
        parsed data and files.
        """
        raise NotImplementedError(".parse() must be overridden.")

从parse方法的注释,也可以看出parse返回的可能是解析后的数据,也有可能是DataAndFiles对象。

parse方法中的参数:stream即为要解析的数据,

parse_context为需要解析时需要提供的配置,


?
1
2
3
4
class DataAndFiles(object):
    def __init__(self, data, files):
        self.data = data
        self.files = files

可以看出DataAndFiles仅仅是data和files的集合。只有MultiPartParser和FileUploadParser才返回DataAndFiles对象。


parser.py一共有以下多种类,JSONParser,YAMLParser,FormParser,MultiPartParser,XMLParser,FileUploadParser。

首先看JSONParser的定义:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class JSONParser(BaseParser):
    """
    Parses JSON-serialized data.
    """
 
    media_type = 'application/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:
            data = stream.read().decode(encoding)
            return json.loads(data)
        except ValueError as exc:
            raise ParseError('JSON parse error - %s' % six.text_type(exc))

通过parse_context获取encoding,然后解码stream,利用json库中的loads方法解析并返回数据。

其实YAMLParser和XMLParser,是跟JSONParser的步骤一样的,只不过调用不同的库来解析数据。


再来看一下通用的FormPaser,用于解析'application/x-www-form-urlencoded'类型的数据,这种数据是POST方法提交数据,默认的格式。它只不过直接被实例化了QueryDict对象。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
0 0