使用UVicorn和FastAPI实现推送功能的完整示例代码:
import asyncio
import uvicorn
from fastapi import FastAPI, WebSocket
app = FastAPI()
async def push_data(websocket: WebSocket):
while True:
await websocket.send_text("Push data")
await asyncio.sleep(5)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
task = asyncio.create_task(push_data(websocket))
try:
while True:
data = await websocket.receive_text()
print(f"Received data: {data}")
except:
task.cancel()
await task
await websocket.close()
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
uvicorn启动:
uvicorn main:app --reload
依赖包安装:
pip install fastapi uvicorn