FastAPI Websocket server
Mon Jan 31 2022 02:31:04 GMT+0000 (Coordinated Universal Time)
Saved by
@aguest
#python
#fastapi
#websocket
from datetime import datetime
import asyncio
from fastapi import FastAPI, WebSocket
app = FastAPI(
title='WebSocket example',
description='WebSocket example',
version='0.0.1'
)
@app.websocket("/task/{task_uuid}") # take a 'task_uuid' URL parameter
async def websocket_page(task_uuid, websocket: WebSocket):
await websocket.accept() # accept connections
i = 0
"""
create a loop to send the value of 'i' every second with a timestamp:
13:30:01 - i is 5
13:30:02 - i is 6
13:30:03 - i is 7
"""
while i < 10:
timestamp = datetime.now().strftime("%H:%M:%S")
await websocket.send_text(f"[{timestamp}] - i is {i}")
i += 1
await asyncio.sleep(1)
content_copyCOPY
Comments