MCPcopy Create free account
hub / github.com/encode/starlette / parse

Method parse

starlette/formparsers.py:250–301  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

248 pass
249
250 async def parse(self) -> FormData:
251 # Parse the Content-Type header to get the multipart boundary.
252 _, params = parse_options_header(self.headers["Content-Type"])
253 charset = params.get(b"charset", "utf-8")
254 if isinstance(charset, bytes):
255 charset = charset.decode("latin-1")
256 self._charset = charset
257 try:
258 boundary = params[b"boundary"]
259 except KeyError:
260 raise MultiPartException("Missing boundary in multipart.")
261
262 # Callbacks dictionary.
263 callbacks: MultipartCallbacks = {
264 "on_part_begin": self.on_part_begin,
265 "on_part_data": self.on_part_data,
266 "on_part_end": self.on_part_end,
267 "on_header_field": self.on_header_field,
268 "on_header_value": self.on_header_value,
269 "on_header_end": self.on_header_end,
270 "on_headers_finished": self.on_headers_finished,
271 "on_end": self.on_end,
272 }
273
274 try:
275 parser = multipart.MultipartParser(boundary, callbacks)
276 # Feed the parser with data from the request.
277 async for chunk in self.stream:
278 parser.write(chunk)
279 # Write file data, it needs to use await with the UploadFile methods
280 # that call the corresponding file methods *in a threadpool*,
281 # otherwise, if they were called directly in the callback methods above
282 # (regular, non-async functions), that would block the event loop in
283 # the main thread.
284 for part, data in self._file_parts_to_write:
285 assert part.file # for type checkers
286 await part.file.write(data)
287 for part in self._file_parts_to_finish:
288 assert part.file # for type checkers
289 await part.file.seek(0)
290 self._file_parts_to_write.clear()
291 self._file_parts_to_finish.clear()
292 parser.finalize()
293 except BaseException as exc:
294 # Close all the files if parsing or reading the request stream fails.
295 for file in self._files_to_close_on_error:
296 file.close()
297 if isinstance(exc, FormParserError):
298 raise MultiPartException("Invalid multipart data.") from exc
299 raise
300
301 return FormData(self.items)

Callers 2

_get_formMethod · 0.95

Calls 8

FormDataClass · 0.90
MultiPartExceptionClass · 0.85
decodeMethod · 0.80
seekMethod · 0.80
getMethod · 0.45
writeMethod · 0.45
clearMethod · 0.45
closeMethod · 0.45