The code below doesn't reach out of the with
. Is there any way I can close the socket when the client disconnects?
import fastapi
import uvicorn
import socket
def gen_video(port):
with socket.socket() as s:
s.connect(("127.0.0.1", port))
while True:
yield s.recv(1024)
app = fastapi.FastAPI()
@app.get("/stream")
async def stream():
return fastapi.responses.StreamingResponse(gen_video(1234), media_type="video/ogg")
if __name__ == "__main__":
uvicorn.run(app, port=8000)