[Python] emit Broadcast with flask_socketio

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a flask server running, and sockets are connection successfully. I want to run a service that monitors stuff on my server, such as GPU usage with GPUMonitorService, and the broadcast that data to all connected sockets. I make the GPU service, and pass in the socketio object. I have an on.connect handler that works as expected. I used these docs for reference https://flask-socketio.readthedocs.io/en/latest/getting_started.html#broadcasting

    from flask import Flask, request, jsonify, send_file
    from flask_socketio import SocketIO

    from services.GPU_Monit import GPUMonitorService

    socketio = SocketIO(...)

    gpu_service = GPUMonitorService(socketio)

    @socketio.on("connect")
    def handle_connect():
    client_id = request.sid # Get the unique socket ID of the client
    print(f"Client connected: {client_id}")
    # Emit the new client's ID to all connected clients
    socketio.emit( # <---this is working
    "new_connection",
    {"socket_id": client_id},
    )


    //GPU_Monit.py

    from flask_socketio import emit

    class GPUMonitorService:
    def __init__(self, socketio):
    self.socketio = socketio
    self.thread = threading.Thread(target=self._monitoring_task, daemon=True)
    self.thread.start()

    def _monitoring_task(self):
    while True:
    try:
    gpu_info = self.get_detailed_gpu_info()
    if gpu_info:
    #This line does run, but the connected sockets are not getting any messages
    emit("gpu_update", gpu_info, broadcast=True)
    except Exception as e:
    print(f"Error in GPU monitoring: {e}")
    time.sleep(10)


    Any thoughts would be appreciated. I'm more familiar with sockets on NodeJS, and Python has some weird things with threads and special async handling that I'm not aware of. Thanks!

    EDIT: Im getting an error 'Working outside of request context.This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.'

    Continue reading...

Compartilhe esta Página