全部數據解析的類都是BaseParser的子類。
python
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對象。json
parse方法中的參數:stream即爲要解析的數據,app
parse_context爲須要解析時須要提供的配置,url
class DataAndFiles(object): def __init__(self, data, files): self.data = data self.files = files
能夠看出DataAndFiles僅僅是data和files的集合。只有MultiPartParser和FileUploadParser才返回DataAndFiles對象。spa
parser.py一共有如下多種類,JSONParser,YAMLParser,FormParser,MultiPartParser,XMLParser,FileUploadParser。code
首先看JSONParser的定義:orm
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的步驟同樣的,只不過調用不一樣的庫來解析數據。ci
再來看一下通用的FormPaser,用於解析'application/x-www-form-urlencoded'類型的數據,這種數據是POST方法提交數據,默認的格式。它只不過直接被實例化了QueryDict對象。get
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