我使用 FastAPI 构建了一个简单的演示项目。我想实时将数据 POST 到服务器(也许
30fps
)。
客户:
while True:
....
res = requests.post(URL, files={'input_data' : input_data})
....
但是,我收到以下错误:
(MaxRetryError: HTTPConnectionPool(host='~~', port=8000): url 超出最大重试次数)
我认为这是由于发出多个请求造成的。我想实时执行请求。我怎样才能做到这一点?
正如@MatsLindh 在评论中指出的那样,您应该使用更合适的协议 - 例如 WebSockets - 而不是
HTTP
来完成此类任务。 FastAPI/Starlette 支持在 websocket
上发送和接收数据(请参阅文档 here 和 here)。下面是使用 websockets
将视频帧从客户端发送到服务器的示例(假设这是您对 30fps
的评论中的任务 - 但是,相同的方法可以应用于发送其他类型的数据)。 OpenCV
用于捕获帧,websockets
库用于连接到 WebSocket 服务器。
服务器.py
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import cv2
import numpy as np
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
# listen for connections
await websocket.accept()
#count = 1
try:
while True:
contents = await websocket.receive_bytes()
arr = np.frombuffer(contents, np.uint8)
frame = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
cv2.imshow('frame', frame)
cv2.waitKey(1)
#cv2.imwrite("frame%d.png" % count, frame)
#count += 1
except WebSocketDisconnect:
cv2.destroyWindow("frame")
print("Client disconnected")
客户端.py
import websockets
import asyncio
import cv2
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
async def main():
# Connect to the server
async with websockets.connect('ws://localhost:8000/ws') as ws:
while True:
success, frame = camera.read()
if not success:
break
else:
ret, buffer = cv2.imencode('.png', frame)
await ws.send(buffer.tobytes())
# Start the connection
asyncio.run(main())