FastAPI 文件必须放在函数参数中的表单之前

Ned*_*d U 5 python-3.6 pydantic 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)
Run Code Online (Sandbox Code Playgroud)

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

curl localhost:8000/test -X POST -F test_file=@"test_file.txt" -F test_item="test"
Run Code Online (Sandbox Code Playgroud)

没有处理这个错误:

{
    "detail": [
        {
            "loc": [
                "body",
                "test_file"
            ],
            "msg": "byte type expected",
            "type": "type_error.bytes"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

唯一的区别是您在 Form 元素之前获取 File。有谁知道为什么会发生这种情况?看起来需要先上传文件再上传表单。也许当 Form 解析 http 表单主体时文件被杀死。我在 FastAPI 文档中没有看到任何关于表单和文件的内容。