from datetime import datetime
import asyncio

from fastapi import FastAPI, WebSocket

app = FastAPI(
    title='WebSocket example',
    description='WebSocket example',

@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 ="%H:%M:%S")
        await websocket.send_text(f"[{timestamp}] - i is {i}")
        i += 1
        await asyncio.sleep(1)
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter