【问题标题】:FastAPI File(s) must be put before form in function parametersFastAPI 文件必须放在函数参数中的表单之前
【发布时间】:2020-08-06 03:50:53
【问题描述】:

我有一个端点,它接受一个文件和一个通过表单主体传递的字符串参数。但我在调试时注意到:

import uvicorn
from fastapi import FastAPI, File, Form

app = FastAPI()


@app.post('/test')
def test(test_item: str = Form(...), test_file: bytes = File(...)):
    return {
        "test_item": test_item,
        "test_file_len": len(test_file),
        "test_file_contents": test_file.decode('utf-8')
    }


if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)

在 test_file.txt 中使用这个简单的 curl 命令,其中包含一些文本:

curl localhost:8000/test -X POST -F test_file=@"test_file.txt" -F test_item="test"

没有解决这个错误:

{
    "detail": [
        {
            "loc": [
                "body",
                "test_file"
            ],
            "msg": "byte type expected",
            "type": "type_error.bytes"
        }
    ]
}

但有趣的是,这确实有效:

import uvicorn
from fastapi import FastAPI, File, Form

app = FastAPI()


@app.post('/test')
def test(test_file: bytes = File(...), test_item: str = Form(...)):
    return {
        "test_item": test_item,
        "test_file_len": len(test_file),
        "test_file_contents": test_file.decode('utf-8')
    }


if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)

唯一的区别是您在表单元素之前获取文件。有人知道为什么会这样吗?看起来需要在表单之前上传文件。当 Form 解析 http 表单正文时,文件可能会被杀死。我在 FastAPI 文档中没有看到任何关于表单和文件的内容。

【问题讨论】:

    标签: python-3.6 fastapi pydantic


    【解决方案1】:

    这在 FastApi 0.43.0 中工作。

    这是https://github.com/tiangolo/fastapi/commit/ab2b86fe2ce8fe15e91aaec179438e24ff7b7ed0中引入的回归

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多