Debian Codegraph @

rest_framework/parsers.py

raw
1 """
2 Parsers are used to parse the content of incoming HTTP requests.
3
4 They give us a generic way of being able to handle various media types
5 on the request, such as form content or json encoded data.
6 """
7
8 import codecs
9 import contextlib
10
11 from django.conf import settings
12 from django.core.files.uploadhandler import StopFutureHandlers
13 from django.http import QueryDict
14 from django.http.multipartparser import ChunkIter
15 from django.http.multipartparser import \
16 MultiPartParser as DjangoMultiPartParser
17 from django.http.multipartparser import MultiPartParserError
18 from django.utils.http import parse_header_parameters
19
20 from rest_framework import renderers
21 from rest_framework.exceptions import ParseError
22 from rest_framework.settings import api_settings
23 from rest_framework.utils import json
24
25
26 class DataAndFiles:
27 def __init__(self, data, files):
28 self.data = data
29 self.files = files
30
31
32 class BaseParser:
33 """
34 All parsers should extend `BaseParser`, specifying a `media_type`
35 attribute, and overriding the `.parse()` method.
36 """
37 media_type = None
38
39 def parse(self, stream, media_type=None, parser_context=None):
40 """
41 Given a stream to read from, return the parsed representation.
42 Should return parsed data, or a `DataAndFiles` object consisting of the
43 parsed data and files.
44 """
45 raise NotImplementedError(".parse() must be overridden.")
46
47
48 class JSONParser(BaseParser):
49 """
50 Parses JSON-serialized data.
51 """
52 media_type = 'application/json'
53 renderer_class = renderers.JSONRenderer
54 strict = api_settings.STRICT_JSON
55
56 def parse(self, stream, media_type=None, parser_context=None):
57 """
58 Parses the incoming bytestream as JSON and returns the resulting data.
59 """
60 parser_context = parser_context or {}
61 encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
62
63 try:
64 decoded_stream = codecs.getreader(encoding)(stream)
65 parse_constant = json.strict_constant if self.strict else None
66 return json.load(decoded_stream, parse_constant=parse_constant)
67 except ValueError as exc:
68 raise ParseError('JSON parse error - %s' % str(exc))
69
70
71 class FormParser(BaseParser):
72 """
73 Parser for form data.
74 """
75 media_type = 'application/x-www-form-urlencoded'
76
77 def parse(self, stream, media_type=None, parser_context=None):
78 """
79 Parses the incoming bytestream as a URL encoded form,
80 and returns the resulting QueryDict.
81 """
82 parser_context = parser_context or {}
83 encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
84 return QueryDict(stream.read(), encoding=encoding)
85
86
87 class MultiPartParser(BaseParser):
88 """
89 Parser for multipart form data, which may include file data.
90 """
91 media_type = 'multipart/form-data'
92
93 def parse(self, stream, media_type=None, parser_context=None):
94 """
95 Parses the incoming bytestream as a multipart encoded form,
96 and returns a DataAndFiles object.
97
98 `.data` will be a `QueryDict` containing all the form parameters.
99 `.files` will be a `QueryDict` containing all the form files.
100 """
101 parser_context = parser_context or {}
102 request = parser_context['request']
103 encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
104 meta = request.META.copy()
105 meta['CONTENT_TYPE'] = media_type
106 upload_handlers = request.upload_handlers
107
108 try:
109 parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
110 data, files = parser.parse()
111 return DataAndFiles(data, files)
112 except MultiPartParserError as exc:
113 raise ParseError('Multipart form parse error - %s' % str(exc))
114
115
116 class FileUploadParser(BaseParser):
117 """
118 Parser for file upload data.
119 """
120 media_type = '*/*'
121 errors = {
122 'unhandled': 'FileUpload parse error - none of upload handlers can handle the stream',
123 'no_filename': 'Missing filename. Request should include a Content-Disposition header with a filename parameter.',
124 }
125
126 def parse(self, stream, media_type=None, parser_context=None):
127 """
128 Treats the incoming bytestream as a raw file upload and returns
129 a `DataAndFiles` object.
130
131 `.data` will be None (we expect request body to be a file content).
132 `.files` will be a `QueryDict` containing one 'file' element.
133 """
134 parser_context = parser_context or {}
135 request = parser_context['request']
136 encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
137 meta = request.META
138 upload_handlers = request.upload_handlers
139 filename = self.get_filename(stream, media_type, parser_context)
140
141 if not filename:
142 raise ParseError(self.errors['no_filename'])
143
144 # Note that this code is extracted from Django's handling of
145 # file uploads in MultiPartParser.
146 content_type = meta.get('HTTP_CONTENT_TYPE',
147 meta.get('CONTENT_TYPE', ''))
148 try:
149 content_length = int(meta.get('HTTP_CONTENT_LENGTH',
150 meta.get('CONTENT_LENGTH', 0)))
151 except (ValueError, TypeError):
152 content_length = None
153
154 # See if the handler will want to take care of the parsing.
155 for handler in upload_handlers:
156 result = handler.handle_raw_input(stream,
157 meta,
158 content_length,
159 None,
160 encoding)
161 if result is not None:
162 return DataAndFiles({}, {'file': result[1]})
163
164 # This is the standard case.
165 possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
166 chunk_size = min([2 ** 31 - 4] + possible_sizes)
167 chunks = ChunkIter(stream, chunk_size)
168 counters = [0] * len(upload_handlers)
169
170 for index, handler in enumerate(upload_handlers):
171 try:
172 handler.new_file(None, filename, content_type,
173 content_length, encoding)
174 except StopFutureHandlers:
175 upload_handlers = upload_handlers[:index + 1]
176 break
177
178 for chunk in chunks:
179 for index, handler in enumerate(upload_handlers):
180 chunk_length = len(chunk)
181 chunk = handler.receive_data_chunk(chunk, counters[index])
182 counters[index] += chunk_length
183 if chunk is None:
184 break
185
186 for index, handler in enumerate(upload_handlers):
187 file_obj = handler.file_complete(counters[index])
188 if file_obj is not None:
189 return DataAndFiles({}, {'file': file_obj})
190
191 raise ParseError(self.errors['unhandled'])
192
193 def get_filename(self, stream, media_type, parser_context):
194 """
195 Detects the uploaded file name. First searches a 'filename' url kwarg.
196 Then tries to parse Content-Disposition header.
197 """
198 with contextlib.suppress(KeyError):
199 return parser_context['kwargs']['filename']
200
201 with contextlib.suppress(AttributeError, KeyError, ValueError):
202 meta = parser_context['request'].META
203 disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION'])
204 if 'filename*' in params:
205 return params['filename*']
206 return params['filename']