python-3.6 - 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 文档中没有看到任何关于表单和文件的内容。
解决方案
这在 FastApi 0.43.0 中工作。
这是在https://github.com/tiangolo/fastapi/commit/ab2b86fe2ce8fe15e91aaec179438e24ff7b7ed0中引入的回归
推荐阅读
- html - HTML 文件找不到引导程序 CSS 文件
- api - 通过 API 修改 Github 配置文件但出现“找不到消息”错误
- angular - Typescript获取对象数组中两列值的数组
- google-apps-script - JSON.stringify.replace 用于更新使用 Gmail 草稿作为模板的邮件合并代码
- c# - 解析json时如何将字符串添加到集合中
- node.js - 如何根据与来自服务器的 id 匹配的对象 ID 显示对象
- python - jupyter 中的 %matplotlib notebook 魔术命令只能间歇性地工作
- ruby-on-rails - Ruby on Rails Active Record Bank 数据库“统一”
- matlab - 不确定如何使用“ODE45”命令修复错误
- python - Python,Django:有没有办法在一个模板中编辑多个数据集