Search code examples
pythonflask-socketio

How to store a message from the client in the server and send it further via some route in Flask


From a web application, this is making a request to the backend application (Python with Flask and flask-socketio). From this route on the backend, an emit should be done to a socketio client standalone application. This works fine, but when the client app sends back a message directly after, I want to retrieve this message and send it back in my route to the web application. The message I get back from the client via a callback will be asynchronous, so how in the simplest manner could this be achieved? Each time I fetch the message from the client, the route has already sent back a reply to the web app without the message.

I fully understand that this flow is usually not normal, but can this be achieved without saving this message into a database, but store it somewhere on the backend and send it back to the web app?


Solution

  • You can use an Event object from the Python standard library.

    from threading import Event
    my_event = Event()
    

    In your Flask route:

    my_event.wait()  # block until the event is signaled
    return socketio_response
    

    In your Socket.IO callback function:

    socketio_response = data
    my_event.set()  # alert the route that a result is now available