diff --git a/docs/web.rst b/docs/web.rst index 44f05fabf32..1f9786c1c7f 100644 --- a/docs/web.rst +++ b/docs/web.rst @@ -742,49 +742,48 @@ that :meth:`Request.post` reads the whole payload in memory, resulting in possib should use :meth:`Request.multipart` which returns a :ref:`multipart reader `:: + @route( async def store_multipart_handler(request): """Handle a multipart form.""" - if request.method == 'POST': - multipart = await request.multipart() - - # /!\ Don't forget to validate your inputs /!\ - - data = {} - - while True: - field = await multipart.next() - if not field: - break - - # You cannot rely on Content-Length if transfer is chunked. - size = 0 - content_type = field.headers.get('CONTENT-TYPE') - - if field.filename: - data['file'] = field.filename - tmp_path = os.path.join("/tmp/", field.filename) - with open(tmp_path, 'wb') as f: - while True: - # 8192 bytes by default. - chunk = await field.read_chunk() - if not chunk: - break - size += len(chunk) - f.write(chunk) - else: - # here is where we handle non-files fields - value = await field.read(decode=True) - if content_type is None or \ - content_type.startswith('text/'): - charset = field.get_charset(default='utf-8') - value = value.decode(charset) - data[field.name] = value - size += len(value) - - return web.Response(text='Thanks {} for uploading {}' - .format(data['name'], data['file'])) - - return web.Response(body=page, content_type="text/html") + multipart = await request.multipart() + + # /!\ Don't forget to validate your inputs /!\ + + data = {} + + while True: + field = await multipart.next() + if not field: + break + + # You cannot rely on Content-Length if transfer is chunked. + size = 0 + content_type = field.headers.get('CONTENT-TYPE') + + if field.filename: + data['file'] = field.filename + tmp_path = os.path.join("/tmp/", field.filename) + with open(tmp_path, 'wb') as f: + while True: + # 8192 bytes by default. + chunk = await field.read_chunk() + if not chunk: + break + size += len(chunk) + f.write(chunk) + else: + # here is where we handle non-files fields + value = await field.read(decode=True) + if content_type is None or \ + content_type.startswith('text/'): + charset = field.get_charset(default='utf-8') + value = value.decode(charset) + data[field.name] = value + size += len(value) + + return web.Response(text='Thanks {} for uploading {}' + .format(data['name'], data['file'])) + .. _aiohttp-web-websockets: