您的位置:首页 > 编程语言 > Go语言

django rest framework - 数据解析

2015-01-15 00:00 162 查看
摘要: parser.py是rest-framework的数据解析模块, 它能够解析大多数的数据格式(json,xml,yaml)
所有数据解析的类都是BaseParser的子类。
class BaseParser(object):"""All parsers should extend `BaseParser`, specifying a `media_type`attribute, and overriding the `.parse()` method."""media_type = Nonedef 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 theparsed data and files."""raise NotImplementedError(".parse() must be overridden.")
从parse方法的注释,也可以看出parse返回的可能是解析后的数据,也有可能是DataAndFiles对象。parse方法中的参数:stream即为要解析的数据,parse_context为需要解析时需要提供的配置,
class DataAndFiles(object):def __init__(self, data, files):self.data = dataself.files = files
可以看出DataAndFiles仅仅是data和files的集合。只有MultiPartParser和FileUploadParser才返回DataAndFiles对象。parser.py一共有以下多种类,JSONParser,YAMLParser,FormParser,MultiPartParser,XMLParser,FileUploadParser。首先看JSONParser的定义:
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对象。
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: