我无法编写函数,该函数可以通过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':'解析正文时出错'}
在服务器端:“ POST / post_text_file HTTP / 1.1” 400错误的请求
答案 0 :(得分:3)
requests.post有一个files
参数,您可以使用它发送如下文件:
import requests
url = "http://localhost:8000/post_text_file"
fin = open('Hello World.txt', 'rb')
files = {'file': fin}
try:
r = requests.post(url, files=files)
finally:
fin.close()
通常,通过request.files
可以访问随请求发送的文件,作为上传文件的字典。
答案 1 :(得分:0)
如果未安装 python-multipart ,则可能会发生这种情况。因此,请确保您已完成:
pip install python-multipart