多部分形式

Falcon的特点是使用 falcon.media.MultipartFormHandler 处理 multipart/form-data media 类型。默认情况下启用此处理程序,允许您使用 req.get_media() 迭代 body parts 在形式上:

form = req.get_media()
for part in form:
    if part.content_type == 'application/json':
        # Body part is a JSON document, do something useful with it
        resp.media = part.get_media()
    elif part.name == 'datafile':
        while True:
            # Do something with the uploaded data (file)
            chunk = part.stream.read(8192)
            if not chunk:
                break
            feed_data(chunk)
    elif part.name == 'imagedata':
        # Store this body part in a file.
        filename = os.path.join(UPLOAD_PATH, part.secure_filename)
        with open(filename, 'wb') as dest:
            part.stream.pipe(dest)
    else:
        # Do something else
        form_data[part.name] = part.text
form = await req.get_media()
async for part in form:
    if part.content_type == 'application/json':
        # Body part is a JSON document, do something useful with it
        resp.media = await part.get_media()
    elif part.name == 'datafile':
        # Do something with the uploaded data (file)
        async for chunk in part.stream:
            await feed_data(chunk)
    elif part.name == 'imagedata':
        # Store this body part in a file.
        filename = os.path.join(UPLOAD_PATH, part.secure_filename)
        async with aiofiles.open(filename, 'wb') as dest:
            await part.stream.pipe(dest)
    else:
        # Do something else
        form_data[part.name] = await part.text

注解

请求流不是一次被读入和缓冲,而是在表单中遍历主体部分时按需使用。

对于每个部件,您可以选择是将整个部件读入内存,还是将其写入文件,或者 upload it to the cloud . Falcon为所有这些场景提供了直接的支持。