django-rest-framework/djangorestframework/parsers.py

259 lines
7.2 KiB
Python
Raw Normal View History

2011-05-10 13:49:28 +04:00
"""
Django supports parsing the content of an HTTP request, but only for form POST requests.
That behavior is sufficient for dealing with standard HTML forms, but it doesn't map well
to general HTTP requests.
2011-03-04 13:28:20 +03:00
We need a method to be able to:
2011-03-04 13:28:20 +03:00
1.) Determine the parsed content on a request for methods other than POST (eg typically also PUT)
2.) Determine the parsed content on a request for media types other than application/x-www-form-urlencoded
and multipart/form-data. (eg also handle multipart/json)
"""
from django.http import QueryDict
2011-05-10 13:49:28 +04:00
from django.http.multipartparser import MultiPartParser as DjangoMultiPartParser
from django.http.multipartparser import MultiPartParserError
2011-05-10 13:49:28 +04:00
from django.utils import simplejson as json
2011-02-19 13:47:26 +03:00
from djangorestframework import status
from djangorestframework.compat import yaml
2011-05-10 13:49:28 +04:00
from djangorestframework.response import ErrorResponse
from djangorestframework.utils.mediatypes import media_type_matches
2011-12-11 22:27:40 +04:00
from xml.etree import ElementTree as ET
from djangorestframework.compat import ETParseError
from xml.parsers.expat import ExpatError
2011-12-11 22:27:40 +04:00
import datetime
import decimal
2011-05-10 13:49:28 +04:00
2011-05-10 13:49:28 +04:00
__all__ = (
'BaseParser',
'JSONParser',
'PlainTextParser',
'FormParser',
'MultiPartParser',
'YAMLParser',
2012-01-11 17:44:11 +04:00
'XMLParser'
2011-05-10 13:49:28 +04:00
)
class BaseParser(object):
2011-05-10 13:49:28 +04:00
"""
All parsers should extend :class:`BaseParser`, specifying a :attr:`media_type` attribute,
and overriding the :meth:`parse` method.
2011-05-10 13:49:28 +04:00
"""
2011-05-19 11:49:57 +04:00
2011-01-26 23:31:47 +03:00
media_type = None
def __init__(self, view):
"""
2011-05-10 13:49:28 +04:00
Initialize the parser with the ``View`` instance as state,
in case the parser needs to access any metadata on the :obj:`View` object.
"""
self.view = view
2011-12-29 17:31:12 +04:00
def can_handle_request(self, content_type):
"""
Returns :const:`True` if this parser is able to deal with the given *content_type*.
2011-12-29 17:31:12 +04:00
The default implementation for this function is to check the *content_type*
argument against the :attr:`media_type` attribute set on the class to see if
2011-05-10 13:49:28 +04:00
they match.
2011-12-29 17:31:12 +04:00
2011-05-10 13:49:28 +04:00
This may be overridden to provide for other behavior, but typically you'll
instead want to just set the :attr:`media_type` attribute on the class.
"""
return media_type_matches(self.media_type, content_type)
def parse(self, stream):
2011-05-10 13:49:28 +04:00
"""
Given a *stream* to read from, return the deserialized output.
Should return a 2-tuple of (data, files).
2011-05-10 13:49:28 +04:00
"""
raise NotImplementedError("BaseParser.parse() Must be overridden to be implemented.")
class JSONParser(BaseParser):
"""
Parses JSON-serialized data.
"""
2011-05-19 11:49:57 +04:00
2011-05-10 13:49:28 +04:00
media_type = 'application/json'
def parse(self, stream):
"""
Returns a 2-tuple of `(data, files)`.
`data` will be an object which is the parsed content of the response.
`files` will always be `None`.
"""
try:
return (json.load(stream), None)
except ValueError, exc:
2011-05-10 13:49:28 +04:00
raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
{'detail': 'JSON parse error - %s' % unicode(exc)})
2011-01-26 11:58:09 +03:00
2012-02-22 02:09:05 +04:00
class YAMLParser(BaseParser):
"""
Parses YAML-serialized data.
"""
2011-12-29 17:31:12 +04:00
2012-02-22 02:09:05 +04:00
media_type = 'application/yaml'
2011-12-29 17:31:12 +04:00
2012-02-22 02:09:05 +04:00
def parse(self, stream):
"""
Returns a 2-tuple of `(data, files)`.
2011-12-29 17:31:12 +04:00
2012-02-22 02:09:05 +04:00
`data` will be an object which is the parsed content of the response.
`files` will always be `None`.
"""
try:
return (yaml.safe_load(stream), None)
except (ValueError, yaml.parser.ParserError), exc:
content = {'detail': 'YAML parse error - %s' % unicode(exc)}
raise ErrorResponse(status.HTTP_400_BAD_REQUEST, content)
2012-01-21 22:33:34 +04:00
2011-04-11 14:54:26 +04:00
class PlainTextParser(BaseParser):
"""
Plain text parser.
"""
2011-05-19 11:49:57 +04:00
2011-05-10 13:49:28 +04:00
media_type = 'text/plain'
2011-04-11 14:54:26 +04:00
def parse(self, stream):
"""
Returns a 2-tuple of `(data, files)`.
2011-12-29 17:31:12 +04:00
`data` will simply be a string representing the body of the request.
`files` will always be `None`.
"""
return (stream.read(), None)
2011-04-11 14:54:26 +04:00
class FormParser(BaseParser):
"""
Parser for form data.
2011-05-13 12:59:36 +04:00
"""
2011-03-10 17:49:11 +03:00
2011-05-10 13:49:28 +04:00
media_type = 'application/x-www-form-urlencoded'
def parse(self, stream):
"""
Returns a 2-tuple of `(data, files)`.
2011-12-29 17:31:12 +04:00
2011-05-19 11:49:57 +04:00
`data` will be a :class:`QueryDict` containing all the form parameters.
`files` will always be :const:`None`.
"""
data = QueryDict(stream.read())
return (data, None)
class MultiPartParser(BaseParser):
"""
Parser for multipart form data, which may include file data.
"""
2011-05-10 13:49:28 +04:00
media_type = 'multipart/form-data'
2011-03-04 13:28:20 +03:00
def parse(self, stream):
"""
Returns a 2-tuple of `(data, files)`.
2011-12-29 17:31:12 +04:00
2011-05-19 11:49:57 +04:00
`data` will be a :class:`QueryDict` containing all the form parameters.
`files` will be a :class:`QueryDict` containing all the form files.
"""
upload_handlers = self.view.request._get_upload_handlers()
try:
django_parser = DjangoMultiPartParser(self.view.request.META, stream, upload_handlers)
return django_parser.parse()
except MultiPartParserError, exc:
raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
{'detail': 'multipart parse error - %s' % unicode(exc)})
2012-01-19 07:59:30 +04:00
2011-12-11 22:27:40 +04:00
class XMLParser(BaseParser):
"""
XML parser.
"""
media_type = 'application/xml'
def parse(self, stream):
"""
Returns a 2-tuple of `(data, files)`.
2012-01-19 07:59:30 +04:00
2011-12-11 22:27:40 +04:00
`data` will simply be a string representing the body of the request.
`files` will always be `None`.
"""
try:
tree = ET.parse(stream)
except (ExpatError, ETParseError, ValueError), exc:
content = {'detail': 'XML parse error - %s' % unicode(exc)}
raise ErrorResponse(status.HTTP_400_BAD_REQUEST, content)
2012-01-11 22:36:43 +04:00
data = self._xml_convert(tree.getroot())
2012-01-12 16:28:32 +04:00
2011-12-11 22:27:40 +04:00
return (data, None)
2012-01-12 16:28:32 +04:00
2012-01-11 22:36:43 +04:00
def _xml_convert(self, element):
"""
2012-01-21 22:33:34 +04:00
convert the xml `element` into the corresponding python object
2012-01-11 22:36:43 +04:00
"""
2012-01-21 22:33:34 +04:00
2012-01-11 22:36:43 +04:00
children = element.getchildren()
2012-01-21 22:33:34 +04:00
2012-01-11 22:36:43 +04:00
if len(children) == 0:
return self._type_convert(element.text)
else:
2012-01-12 16:28:32 +04:00
# if the fist child tag is list-item means all children are list-item
if children[0].tag == "list-item":
2012-01-11 22:36:43 +04:00
data = []
for child in children:
2012-01-21 22:33:34 +04:00
data.append(self._xml_convert(child))
else:
2012-01-12 16:28:32 +04:00
data = {}
for child in children:
data[child.tag] = self._xml_convert(child)
2012-01-11 22:36:43 +04:00
return data
2012-01-21 22:33:34 +04:00
2011-12-29 17:31:12 +04:00
def _type_convert(self, value):
2011-12-11 22:27:40 +04:00
"""
2011-12-29 17:31:12 +04:00
Converts the value returned by the XMl parse into the equivalent
2011-12-11 22:27:40 +04:00
Python type
2012-01-19 07:59:30 +04:00
"""
if value is None:
2011-12-11 22:27:40 +04:00
return value
2012-01-19 07:59:30 +04:00
2011-12-11 22:27:40 +04:00
try:
2012-01-21 22:33:34 +04:00
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
2011-12-11 22:27:40 +04:00
except ValueError:
pass
2012-01-19 07:59:30 +04:00
2011-12-11 22:27:40 +04:00
try:
return int(value)
except ValueError:
pass
2012-01-19 07:59:30 +04:00
2011-12-11 22:27:40 +04:00
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
pass
2012-01-19 07:59:30 +04:00
2011-12-11 22:27:40 +04:00
return value
2012-01-21 22:33:34 +04:00
DEFAULT_PARSERS = (
JSONParser,
FormParser,
MultiPartParser,
XMLParser
)
2012-02-22 02:09:05 +04:00
if yaml:
DEFAULT_PARSERS += (YAMLParser, )
else:
YAMLParser = None