Skip to content

Instantly share code, notes, and snippets.

@amitrahav
Created May 14, 2021 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitrahav/c6ceecb684be3d2a30e55720ec93508f to your computer and use it in GitHub Desktop.
Save amitrahav/c6ceecb684be3d2a30e55720ec93508f to your computer and use it in GitHub Desktop.
SocketVsSSE
from fastapi import FastAPI
from sse_starlette.sse import EventSourceResponse
from typing import AsyncGenerator
import asyncio
import json
# Creating my app
app = FastAPI()
progress_bar = ["10", "30", "50", "60", "80", "100"]
async def subscribe() -> AsyncGenerator:
for progress in progress_bar: # This function in real can be a redis subscribtion
await asyncio.sleep(2)
# Sending a new message to client:
# The event is set with a name: "pipline_progress"
# The event data contains all the details I need to know about the event accuring
yield {"event": "pipeline_progress", "data": {"progress" : progress}}
@app.get("/videos/subscribe")
async def stram_sse():
# This function is mapped for the url which the inital connection request form client sends to
return EventSourceResponse(subscribe())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment