小编pro*_*Sun的帖子

使用 Python 发送和接收文件:FastAPI 和请求

我正在尝试使用请求将文件上传到 FastAPI 服务器。

我已将问题归结为最简单的组件。

客户端使用请求:

import requests

files = {'file': ('foo.txt', open('./foo.txt', 'rb'))}
response = requests.post('http://127.0.0.1:8000/file', files=files)
print(response)
print(response.json())
Run Code Online (Sandbox Code Playgroud)

服务器使用fastapi:

from fastapi import FastAPI, File, UploadFile
import uvicorn

app = FastAPI()

@app.post('/file')
def _file_upload(my_file: UploadFile = File(...)):
    print(my_file)

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, log_level="debug")
Run Code Online (Sandbox Code Playgroud)

安装的软件包:

  • 快点
  • python-multipart
  • 独角兽
  • 要求

客户端输出:<Response [422]> {'detail': [{'loc': ['query', 'my_file'], 'msg': 'field required', 'type': 'value_error.missing'}] }

服务器输出:信息:127.0.0.1:37520 - “POST /file HTTP/1.1” 422 不可处理的实体

我在这里缺少什么?

python python-3.x python-requests fastapi

6
推荐指数
1
解决办法
2189
查看次数

标签 统计

fastapi ×1

python ×1

python-3.x ×1

python-requests ×1