相关疑难解决方法(0)

FastAPI UploadFile 与 Flask 相比慢

我创建了一个端点,如下所示:

@app.post("/report/upload")
def create_upload_files(files: UploadFile = File(...)):
        try:
            with open(files.filename,'wb+') as wf:
                wf.write(file.file.read())
                wf.close()
        except Exception as e:
            return {"error": e.__str__()}
Run Code Online (Sandbox Code Playgroud)

它是用 uvicorn 启动的:

../venv/bin/uvicorn test_upload:app --host=0.0.0.0 --port=5000 --reload
Run Code Online (Sandbox Code Playgroud)

我正在执行一些测试,使用 Python 请求上传大约100 MB的文件,大约需要 128 秒:

../venv/bin/uvicorn test_upload:app --host=0.0.0.0 --port=5000 --reload
Run Code Online (Sandbox Code Playgroud)

我使用 Flask 通过 API 端点测试了相同的上传脚本,大约需要 0.5 秒:

f = open(sys.argv[1],"rb").read()
hex_convert = binascii.hexlify(f)
items = {"files": hex_convert.decode()}
start = time.time()
r = requests.post("http://192.168.0.90:5000/report/upload",files=items)
end = time.time() - start
print(end)
Run Code Online (Sandbox Code Playgroud)

我做错了什么吗?

python upload file-upload starlette fastapi

7
推荐指数
1
解决办法
9998
查看次数

使用 FastAPI 上传文件返回错误 422

我正在使用官方文档中的示例: https: //fastapi.tiangolo.com/tutorial/request-files/#import-file

服务器代码:

@app.post("/uploadfile")
async def create_upload_file(data: UploadFile = File(...)):
    print("> uploaded file:",data.filename)
    return {"filename": data.filename}
Run Code Online (Sandbox Code Playgroud)

客户端代码:

files = {'upload_file': open('config.txt', 'rb')}
resp = requests.post(
        url = URL,
        files = files)
print(resp.json())
Run Code Online (Sandbox Code Playgroud)

问题是服务器总是响应 422 错误:

{'detail': [{'loc': ['body', 'data'], 'msg': 'field required', 'type': 'value_error.missing'}]}
Run Code Online (Sandbox Code Playgroud)

我在服务器和客户端上都使用 Python 3,并且 python-multipart 包已经安装。

有人可以告诉我我做错了什么,我错过了什么,我应该如何修复代码?

非常感谢任何提示。

python file-upload http-status-code-422 fastapi

4
推荐指数
1
解决办法
4196
查看次数

如何在 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
查看次数