Drop .parse_string_or_stream() - keep API minimal.

This commit is contained in:
Tom Christie 2012-10-17 22:07:56 +01:00
parent 6717d654d0
commit 99d48f9003
5 changed files with 20 additions and 29 deletions

View File

@ -91,11 +91,11 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
# Custom parsers # Custom parsers
To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse_stream(self, stream, parser_context)` method. To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, parser_context)` method.
The method should return the data that will be used to populate the `request.DATA` property. The method should return the data that will be used to populate the `request.DATA` property.
The arguments passed to `.parse_stream()` are: The arguments passed to `.parse()` are:
### stream ### stream
@ -116,7 +116,7 @@ The following is an example plaintext parser that will populate the `request.DAT
media_type = 'text/plain' media_type = 'text/plain'
def parse_stream(self, stream, parser_context=None): def parse(self, stream, parser_context=None):
""" """
Simply return a string representing the body of the request. Simply return a string representing the body of the request.
""" """
@ -124,7 +124,7 @@ The following is an example plaintext parser that will populate the `request.DAT
## Uploading file content ## Uploading file content
If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse_stream()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property. If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property.
For example: For example:
@ -133,7 +133,7 @@ For example:
A naive raw file upload parser. A naive raw file upload parser.
""" """
def parse_stream(self, stream, parser_context): def parse(self, stream, parser_context):
content = stream.read() content = stream.read()
name = 'example.dat' name = 'example.dat'
content_type = 'application/octet-stream' content_type = 'application/octet-stream'

View File

@ -134,12 +134,15 @@ We've now got a few comment instances to play with. Let's take a look at serial
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`. At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
stream = JSONRenderer().render(serializer.data) content = JSONRenderer().render(serializer.data)
stream content
# '{"id": 1, "email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}' # '{"id": 1, "email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}'
Deserialization is similar. First we parse a stream into python native datatypes... Deserialization is similar. First we parse a stream into python native datatypes...
import StringIO
stream = StringIO.StringIO(content)
data = JSONParser().parse(stream) data = JSONParser().parse(stream)
...then we restore those native datatypes into to a fully populated object instance. ...then we restore those native datatypes into to a fully populated object instance.

View File

@ -21,7 +21,6 @@ from xml.etree import ElementTree as ET
from xml.parsers.expat import ExpatError from xml.parsers.expat import ExpatError
import datetime import datetime
import decimal import decimal
from io import BytesIO
class DataAndFiles(object): class DataAndFiles(object):
@ -33,29 +32,18 @@ class DataAndFiles(object):
class BaseParser(object): class BaseParser(object):
""" """
All parsers should extend `BaseParser`, specifying a `media_type` All parsers should extend `BaseParser`, specifying a `media_type`
attribute, and overriding the `.parse_stream()` method. attribute, and overriding the `.parse()` method.
""" """
media_type = None media_type = None
def parse(self, string_or_stream, parser_context=None): def parse(self, stream, parser_context=None):
"""
The main entry point to parsers. This is a light wrapper around
`parse_stream`, that instead handles both string and stream objects.
"""
if isinstance(string_or_stream, basestring):
stream = BytesIO(string_or_stream)
else:
stream = string_or_stream
return self.parse_stream(stream, parser_context)
def parse_stream(self, stream, parser_context=None):
""" """
Given a stream to read from, return the deserialized output. Given a stream to read from, return the deserialized output.
Should return parsed data, or a DataAndFiles object consisting of the Should return parsed data, or a DataAndFiles object consisting of the
parsed data and files. parsed data and files.
""" """
raise NotImplementedError(".parse_stream() must be overridden.") raise NotImplementedError(".parse() must be overridden.")
class JSONParser(BaseParser): class JSONParser(BaseParser):
@ -65,7 +53,7 @@ class JSONParser(BaseParser):
media_type = 'application/json' media_type = 'application/json'
def parse_stream(self, stream, parser_context=None): def parse(self, stream, parser_context=None):
""" """
Returns a 2-tuple of `(data, files)`. Returns a 2-tuple of `(data, files)`.
@ -85,7 +73,7 @@ class YAMLParser(BaseParser):
media_type = 'application/yaml' media_type = 'application/yaml'
def parse_stream(self, stream, parser_context=None): def parse(self, stream, parser_context=None):
""" """
Returns a 2-tuple of `(data, files)`. Returns a 2-tuple of `(data, files)`.
@ -105,7 +93,7 @@ class FormParser(BaseParser):
media_type = 'application/x-www-form-urlencoded' media_type = 'application/x-www-form-urlencoded'
def parse_stream(self, stream, parser_context=None): def parse(self, stream, parser_context=None):
""" """
Returns a 2-tuple of `(data, files)`. Returns a 2-tuple of `(data, files)`.
@ -123,7 +111,7 @@ class MultiPartParser(BaseParser):
media_type = 'multipart/form-data' media_type = 'multipart/form-data'
def parse_stream(self, stream, parser_context=None): def parse(self, stream, parser_context=None):
""" """
Returns a DataAndFiles object. Returns a DataAndFiles object.
@ -148,7 +136,7 @@ class XMLParser(BaseParser):
media_type = 'application/xml' media_type = 'application/xml'
def parse_stream(self, stream, parser_context=None): def parse(self, stream, parser_context=None):
try: try:
tree = ET.parse(stream) tree = ET.parse(stream)
except (ExpatError, ETParseError, ValueError), exc: except (ExpatError, ETParseError, ValueError), exc:

View File

@ -27,7 +27,7 @@ factory = RequestFactory()
class PlainTextParser(BaseParser): class PlainTextParser(BaseParser):
media_type = 'text/plain' media_type = 'text/plain'
def parse_stream(self, stream, parser_context=None): def parse(self, stream, parser_context=None):
""" """
Returns a 2-tuple of `(data, files)`. Returns a 2-tuple of `(data, files)`.

View File

@ -158,7 +158,7 @@ class APIView(View):
def get_parser_context(self, http_request): def get_parser_context(self, http_request):
""" """
Returns a dict that is passed through to Parser.parse_stream(), Returns a dict that is passed through to Parser.parse(),
as the `parser_context` keyword argument. as the `parser_context` keyword argument.
""" """
return { return {