我无法编写可以通过 POST 请求获取 .txt 文件的函数。
我有一个 .txt 文件,其中包含以下短语:Hello World!
服务器端:
from fastapi import FastAPI, File
from starlette.requests import Request
import io
app = FastAPI()
@app.post("/post_text_file")
def text_function(request: Request,
file: bytes = File(...)):
text = open(io.BytesIO(file), "r").read()
return text # Hello World!
客户端:
import requests
url = 'http://localhost:8000/post_text_file'
r = requests.post(url,data=open('Hello World.txt'))
在运行命令 uvicorn main:app 并在客户端运行代码后,我得到下一个答案:
在客户端:{'detail': 'There was an error parsing the body'}
在服务器端:“POST /post_text_file HTTP/1.1”400 错误请求