Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

500
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda