Skip to content
Advertisement

Push live updates through Socket

I need to pass live data from a python script to my server (made with FastApi) and from this server I need to pass all of them to a client (made with Angular).

Currently I’m doing Http PUT requests from my script and then I’m using Websocket to pass the updates to the client.

The problem is that whenever my server socket is connected, I can’t receive any http requests from my script.

If this solution is not viable, what others might be? And why?

I share my dummy code:

script.py

import requests
import time

if __name__ == "__main__":
    while True:
        headers = {"Content-Type": "application/json"}
        url = "http://localhost:8000/dummy"
        requests.put(url, data={"dummy": "OK"}, headers=headers)
        
        time.sleep(1)

myserver.py

from queue import Queue
from fastapi import FastAPI, WebSocket
from starlette.middleware.cors import CORSMiddleware
import uvicorn

queue = Queue()
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], expose_headers=["*"])


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()

    while True:
        msg = queue.get()
        await websocket.send_json(data=msg)


@app.put("/dummy")
async def update(dummy):
    queue.put(dummy)

if __name__ == "__main__":
  uvicorn.run("myserver:app", host='0.0.0.0', port=8000)

Client implementation is irrelevant.

Advertisement

Answer

I used a Socket to transmit data from the script to my server and a WebSocket to transmit data from my server to the client.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement