Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

499
Views
Python websocket with FastAPI does not return data immediately

I created a websocket connection with FastAPI to "stream" data which comes from a tedious calculation. The data chunks should be send as soon as they are available and not altogether at the very end. In the following code snipped shows my problem simplified. sleep() here shall simulate the calculation time between the resulting data.

from fastapi import FastAPI, WebSocket
import uvicorn
from time import sleep

app = FastAPI()

@app.websocket("/")
async def endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        command = await websocket.receive_text()
        if command == "getData":
            data = {"name": "NAME1", "result": "ABC"}
            await websocket.send_json(data)
            sleep(3)
            data = {"name": "NAME2", "result": "DEF"}
            await websocket.send_json(data)
            sleep(3)
            data = {"name": "NAME3", "result": "GHI"}
            await websocket.send_json(data)

if __name__ == "__main__":
    uvicorn.run("api:app", host="127.0.0.1", port=8000, reload=True)

Problem is when executing this code the client receives no data for 6 seconds and afterwards all the data is transmitted at once. Why is this and how can I make the data chunks being send back one by one as soon as they are available?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

time.sleep is a blocking operation, so even the event loop is suspended in the current thread.

Try using asyncio.sleep which is non-blocking.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!