【问题标题】:Send and receive file using Python: FastAPI and requests使用 Python 发送和接收文件:FastAPI 和请求
【发布时间】:2021-03-14 02:06:01
【问题描述】:

我正在尝试使用请求将文件上传到 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())

使用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")

已安装的软件包:

  • fastapi
  • python-multipart
  • 独角兽
  • 请求

客户端输出: {'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


    【解决方案1】:

    FastAPI 需要 my_file 字段中的文件,而您将其发送到 file 字段。

    应该是这样的

    import requests
    
    url = "http://127.0.0.1:8000/file"
    files = {'my_file': open('README.md', 'rb')}
    res = requests.post(url, files=files)

    此外,您不需要 元组 来管理上传文件(我们正在处理简单的上传,对吗?)

    【讨论】:

      【解决方案2】:

      从您的请求中删除“foo.txt”。

      应该是这样的

      files = {'file': open('./foo.txt', 'rb')}
      

      【讨论】:

      猜你喜欢
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多