python 从FastAPI返回多个文件

cuxqih21  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(286)

使用fastapi,我不知道如何发送多个文件作为响应。

from fastapi import FastAPI, Response

app = FastAPI()

@app.get("/image_from_id/")
async def image_from_id(image_id: int):

    # Get image from the database
    img = ...
    return Response(content=img, media_type="application/png")

字符串
然而,我不确定发送图像列表是什么样子的。理想情况下,我想这样做:

@app.get("/images_from_ids/")
async def image_from_id(image_ids: List[int]):

    # Get a list of images from the database
    images = ...
    return Response(content=images, media_type="multipart/form-data")


但是,这将返回错误

def render(self, content: typing.Any) -> bytes:
        if content is None:
            return b""
        if isinstance(content, bytes):
            return content
>       return content.encode(self.charset)
E       AttributeError: 'list' object has no attribute 'encode'

oipij1gg

oipij1gg1#

我在Python 3和最新的fastapi上对@kia的答案有一些问题,所以这里是我得到的一个修复,它包括BytesIO而不是Stringio,响应属性的修复和顶级归档文件夹的删除

import os
import zipfile
import io

def zipfiles(filenames):
    zip_filename = "archive.zip"

    s = io.BytesIO()
    zf = zipfile.ZipFile(s, "w")

    for fpath in filenames:
        # Calculate path for file in zip
        fdir, fname = os.path.split(fpath)

        # Add file, at correct path
        zf.write(fpath, fname)

    # Must close zip for all contents to be written
    zf.close()

    # Grab ZIP file from in-memory, make response with correct MIME-type
    resp = Response(s.getvalue(), media_type="application/x-zip-compressed", headers={
        'Content-Disposition': f'attachment;filename={zip_filename}'
    })

    return resp

@app.get("/image_from_id/")
async def image_from_id(image_id: int):

    # Get image from the database
    img = ...
    return zipfiles(img)

字符串

mwg9r5ms

mwg9r5ms2#

此外,您可以即时创建zip,并使用StreamingResponse对象将其流回给用户:

import os
import zipfile
import io
from fastapi.responses import StreamingResponse

zip_subdir = "/some_local_path/of_files_to_compress"

def zipfile(filenames):
    zip_io = io.BytesIO()
    with zipfile.ZipFile(zip_io, mode='w', compression=zipfile.ZIP_DEFLATED) as temp_zip:
        for fpath in filenames:
            # Calculate path for file in zip
            fdir, fname = os.path.split(fpath)
            zip_path = os.path.join(zip_subdir, fname)
            # Add file, at correct path
            temp_zip.write(fpath, zip_path)
    return StreamingResponse(
        iter([zip_io.getvalue()]), 
        media_type="application/x-zip-compressed", 
        headers = { "Content-Disposition": f"attachment; filename=images.zip"}
    )

字符串

jdg4fx2g

jdg4fx2g3#

压缩是最好的选择,将有相同的结果在所有浏览器。你可以压缩文件动态。

import os
import zipfile
import StringIO

def zipfiles(filenames):
    zip_subdir = "archive"
    zip_filename = "%s.zip" % zip_subdir

    # Open StringIO to grab in-memory ZIP contents
    s = StringIO.StringIO()
    # The zip compressor
    zf = zipfile.ZipFile(s, "w")

    for fpath in filenames:
        # Calculate path for file in zip
        fdir, fname = os.path.split(fpath)
        zip_path = os.path.join(zip_subdir, fname)

        # Add file, at correct path
        zf.write(fpath, zip_path)

    # Must close zip for all contents to be written
    zf.close()

    # Grab ZIP file from in-memory, make response with correct MIME-type
    resp = Response(s.getvalue(), mimetype = "application/x-zip-compressed")
    # ..and correct content-disposition
    resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename

    return resp

@app.get("/image_from_id/")
async def image_from_id(image_id: int):

    # Get image from the database
    img = ...
    return zipfiles(img)

字符串
作为替代,你可以使用base64编码来嵌入一个(非常小的)图像到json响应中。但我不推荐这样做。
你也可以使用MIME/multipart,但请记住,我是为电子邮件和/或POST传输到HTTP服务器而创建的。它从来没有打算在HTTP事务的客户端接收和解析。一些浏览器支持它,另一些不支持。(所以我认为你也不应该使用它)

相关问题