首页 > 解决方案 > FastAPI 文件必须放在函数参数中的表单之前

问题描述

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

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)

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

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 元素之前获取 File。有人知道为什么会这样吗?看起来需要在表单之前上传文件。当 Form 解析 http 表单正文时,文件可能会被杀死。我在 FastAPI 文档中没有看到任何关于表单和文件的内容。

标签: python-3.6fastapipydantic

解决方案



推荐阅读