Python 上传多个文件上传文件FastAPI 例子
这是我的密码:Python 上传多个文件上传文件FastAPI 例子,python,python-asyncio,fastapi,httpx,Python,Python Asyncio,Fastapi,Httpx,这是我的密码: from typing import List from fastapi import FastAPI, File, UploadFile import asyncio import concurrent.futures app = FastAPI() @app.post("/send_images") async def update_item( files: List[UploadFile] = File(...), ): return
from typing import List
from fastapi import FastAPI, File, UploadFile
import asyncio
import concurrent.futures
app = FastAPI()
@app.post("/send_images")
async def update_item(
files: List[UploadFile] = File(...),
):
return {"res": len(files)}
我向该服务器发送请求时使用(这些特定URL仅在此处举例):
我试图加载包含在URL中的图像,然后将它们成批地发送到FastAPI服务器。但它不起作用。
我得到以下错误:
{"detail":[{"loc":["body","files"],"msg":"field required","type":"value_error.missing"}]}
如何解决问题并能够通过httpx将多个文件发送到FastAPI?问题是httpx 0.13.3不支持多个文件上载,因为此参数需要字典,而字典不能具有相同的键值 我们可以使用这个pull请求来解决这个问题(现在它也可以接受List[Tuple[str,FileTypes]]) 更新: 这个问题现在解决了 更新2: 在这里,我展示了如何将httpx用于不同的请求:
async def request_post_batch(fastapi_url: str, url_content_batch: List[BinaryIO]) -> httpx.Response:
"""
Send batch to FastAPI server.
"""
async with httpx.AsyncClient(timeout=httpx.Timeout(100.0)) as client:
r = await client.post(
fastapi_url,
files=[('bytes_image', url_content) for url_content in url_content_batch]
)
return r
async def request_post_logs(logstash_url: str, logs: List[Dict]) -> httpx.Response:
"""
Send logs to logstash
"""
async with httpx.AsyncClient(timeout=httpx.Timeout(100.0)) as client:
r = await client.post(
logstash_url,
json=logs
)
return r
我猜想,当您通过
httpx.post
请求传递字典时,您的端点需要一个文件列表。尝试类似于文件=[f for f in download_files]
,顺便说一句,在https.post文件中发送它们之前,您似乎没有下载它们。为什么您认为我不下载URL?我使用httpx.get。所以,是的,这是httpx模块限制!现在它不能在post请求中发送多个文件!对不起,我看错了,虽然那个列表仍然是上面的列表。另外,我不认为这是httpx的局限性。表示它接受带有元组的字典。那行吗?例句,例句,例句:-)请问:-)你想要什么样的例句?
async def request_post_batch(fastapi_url: str, url_content_batch: List[BinaryIO]) -> httpx.Response:
"""
Send batch to FastAPI server.
"""
async with httpx.AsyncClient(timeout=httpx.Timeout(100.0)) as client:
r = await client.post(
fastapi_url,
files=[('bytes_image', url_content) for url_content in url_content_batch]
)
return r
async def request_post_logs(logstash_url: str, logs: List[Dict]) -> httpx.Response:
"""
Send logs to logstash
"""
async with httpx.AsyncClient(timeout=httpx.Timeout(100.0)) as client:
r = await client.post(
logstash_url,
json=logs
)
return r