2

I'm refactoring a project to move from Flask with flask-socketio to FastAPI with async. Two main reasons for this are to stop using threads to do what async can do, and also to keep in line with other developers at work. Client side is React with Redux.

Trying to set up a basic 'heartbeat' on the server-side that sends a 0/1 signal each second to all clients. Can't seem to figure out how to do it. I have tried using the StreamingResponse() method, but it just waits for the function given to complete then sends a whole stack of ones and zeros.

Any ideas on how to set up an 'always running' function with FastAPI that live streams simple data? I have 3 functions that need to do this.

I've also looked into flask-sse, but it requires redis, which I'd rather avoid.

Fonty
  • 239
  • 2
  • 11
  • Shouldn't the clients be supposed to actively send something to the server if you want a heartbeat? – jbndlr Mar 25 '20 at 22:47
  • The old version used sockets to do this. The server had a heartbeat thread that was always running and sent a heartbeat signal via sockets to all listening. Clients saw the heartbeat and update accordingly. It was useful to see if other processes the server ran in the same manner (some we somewhat intensive) had fallen into a slow state but was still able to be connected to. It was reasonably simple. And this might be the issue in trying to avoid websockets and stick purely with HTTP – Fonty Mar 25 '20 at 22:58
  • Also, there are other methods to do SSE, but i'm hoping to reduce the learning curve and find a good reliable, not too complex package/tool to implement. – Fonty Mar 25 '20 at 23:00
  • Maybe socket.io is an option then, I heard people using it to trigger UI updates from the server. – jbndlr Mar 25 '20 at 23:14
  • Yeah. I can use socket.io on the client side (although it would be nice to have pure hhtp server sent events) but I have to find a socekt package that works with async on the server side that won't take an age to learn – Fonty Mar 25 '20 at 23:30
  • 1
    why don't you make a [websocket enpoint](https://fastapi.tiangolo.com/advanced/websockets/) in your FastAPI app ? – Thomasleveil Mar 30 '20 at 11:09
  • @Thomasleveil - what a neat idea! I clearly hadn't read through the docs enough! – Fonty Apr 07 '20 at 07:11
  • Examples on how to achieve something like that can be found [here](https://stackoverflow.com/a/70996841/17865804), as well as [here](https://stackoverflow.com/a/70626324/17865804) and [here](https://stackoverflow.com/a/75760884/17865804) – Chris Apr 24 '23 at 12:31

1 Answers1

1

Not a real solution for the question, but sockets might be unavoidable. Since I'm using FastAPI anyway, I'll just use the 'built-in' web sockets. I followed @Thomasleveil and have a nicely functioning app now.

Fonty
  • 239
  • 2
  • 11