aboutsummaryrefslogtreecommitdiffstats
path: root/djangorestframework/parsers.py
diff options
context:
space:
mode:
authorCraig Blaszczyk2011-12-11 18:27:40 +0000
committerCraig Blaszczyk2011-12-11 18:27:40 +0000
commit0632e946f977609ca6d6f4272f02c72dee1f49be (patch)
treeb63fecb4220086fa5a673ce1a2780f86682110f9 /djangorestframework/parsers.py
parentb71a24437a3504b3edf19153576d5a2e92c84bd2 (diff)
downloaddjango-rest-framework-0632e946f977609ca6d6f4272f02c72dee1f49be.tar.bz2
add xml parser
Diffstat (limited to 'djangorestframework/parsers.py')
-rw-r--r--djangorestframework/parsers.py58
1 files changed, 56 insertions, 2 deletions
diff --git a/djangorestframework/parsers.py b/djangorestframework/parsers.py
index 2ff64bd3..09e7f4d0 100644
--- a/djangorestframework/parsers.py
+++ b/djangorestframework/parsers.py
@@ -19,6 +19,9 @@ from djangorestframework import status
from djangorestframework.compat import yaml
from djangorestframework.response import ErrorResponse
from djangorestframework.utils.mediatypes import media_type_matches
+from xml.etree import ElementTree as ET
+import datetime
+import decimal
__all__ = (
@@ -28,6 +31,7 @@ __all__ = (
'FormParser',
'MultiPartParser',
'YAMLParser',
+ 'XMLParser'
)
@@ -167,10 +171,60 @@ class MultiPartParser(BaseParser):
raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
{'detail': 'multipart parse error - %s' % unicode(exc)})
return django_parser.parse()
+
+
+class XMLParser(BaseParser):
+ """
+ XML parser.
+ """
+
+ media_type = 'application/xml'
+
+ def parse(self, stream):
+ """
+ Returns a 2-tuple of `(data, files)`.
+
+ `data` will simply be a string representing the body of the request.
+ `files` will always be `None`.
+ """
+ data = {}
+ tree = ET.parse(stream)
+ for child in tree.getroot().getchildren():
+ data[child.tag] = self._type_convert(child.text)
+
+ return (data, None)
+
+ def _type_convert(self, value):
+ """
+ Converts the value returned by the XMl parse into the equivalent
+ Python type
+ """
+ if value is None:
+ return value
+
+ try:
+ return datetime.datetime.strptime(value,'%Y-%m-%d %H:%M:%S')
+ except ValueError:
+ pass
+
+ try:
+ return int(value)
+ except ValueError:
+ pass
+
+ try:
+ return decimal.Decimal(value)
+ except decimal.InvalidOperation:
+ pass
+
+ return value
+
DEFAULT_PARSERS = ( JSONParser,
FormParser,
- MultiPartParser )
+ MultiPartParser,
+ XMLParser
+ )
if YAMLParser:
- DEFAULT_PARSERS += ( YAMLParser, )
+ DEFAULT_PARSERS += ( YAMLParser, ) \ No newline at end of file