fastapi 返回 多个文件
时间: 2024-12-16 19:03:29 浏览: 3
在FastAPI中,返回多个文件通常发生在需要同时发送多个独立的数据流,比如用户请求下载多个附件的情况。这可以通过将每个文件内容转换成`StreamingResponse`对象,并将它们作为一个列表返回来实现。下面是一个简单的示例:
```python
from fastapi.responses import StreamingResponse
def get_multiple_files(file1_path: str, file2_path: str):
def generate_file(file_path):
with open(file_path, "rb") as f:
yield from iter(lambda: f.read(8192), b"")
files = [
StreamingResponse(generate_file(file1_path), media_type="application/octet-stream", filename="file1.txt"),
StreamingResponse(generate_file(file2_path), media_type="application/octet-stream", filename="file2.txt")
]
return files
# 调用函数并处理返回值
async def download():
response = await get_multiple_files("/path/to/file1", "/path/to/file2")
for resp in response:
await resp.iterate()
阅读全文