相关疑难解决方法(0)

使用fastapi上传文件

我根据官方文档使用fastapi上传文件,就像:

@app.post("/create_file/")
async def create_file(file: UploadFile=File(...)):
      file2store = await file.read()
      # some code to store the BytesIO(file2store) to the other database
Run Code Online (Sandbox Code Playgroud)

当我使用 python requests lib 发送请求时:

f = open(".../file.txt", 'rb')
files = {"file": (f.name, f, "multipart/form-data")}
requests.post(url="SERVER_URL/create_file", files=files)
Run Code Online (Sandbox Code Playgroud)

file2store 始终为空。有时(很少见),它可以获取文件字节,但几乎所有时间都是空的,所以我无法在另一个数据库上恢复文件。我还尝试了 'bytes' 而不是 'UploadFile',我得到了相同的结果。我的代码有什么地方不对,还是我使用fastapi上传文件的方式有问题?我google了很长时间,但没有成功。所以我在这里提出问题,希望知道答案的人可以帮助我。谢谢

python file-upload fastapi

8
推荐指数
2
解决办法
2万
查看次数

如何在 FastAPI POST 请求中同时添加文件和 JSON 正文?

具体来说,我希望以下示例能够正常工作:

from typing import List
from pydantic import BaseModel
from fastapi import FastAPI, UploadFile, File


app = FastAPI()


class DataConfiguration(BaseModel):
    textColumnNames: List[str]
    idColumn: str


@app.post("/data")
async def data(dataConfiguration: DataConfiguration,
               csvFile: UploadFile = File(...)):
    pass
    # read requested id and text columns from csvFile
Run Code Online (Sandbox Code Playgroud)

如果这不是 POST 请求的正确方法,请告诉我如何从 FastAPI 中上传的 CSV 文件中选择所需的列。

python http http-post pydantic fastapi

2
推荐指数
3
解决办法
1659
查看次数

标签 统计

fastapi ×2

python ×2

file-upload ×1

http ×1

http-post ×1

pydantic ×1