phanny
phanny

Reputation: 617

How to use flask-socketio for python scripts which do not have http request

I have been following this and this link to have communication between client and server. My basic idea is to pop up notifications which I am currently emitting from app.py(my flask application). But, I also have separate python scripts which do no have http requests. I want to send notifications to the client(browser) from these scripts also. So I was thinking of sending messages to app.py from my other python scripts and doing emit from app.py. Is there a better alternative to achieve this ?

Upvotes: 2

Views: 976

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67502

I was thinking of sending messages to app.py from my other python scripts and doing emit from app.py

This is actually how Flask-SocketIO does this.

You have to run a message queue, typically Redis or RabbitMQ, that is accessible to your server and your external scripts. Then in your server, you create your SocketIO object as follows:

socketio = SocketIO(app, message_queue='redis://')

And in your scripts, you create it as follows:

socketio = SocketIO(message_queue='redis://')

Obviously you can change the message queue URL to match what you are using.

The first object is a fully enabled server, that attaches to your app Flask instance. The second, is a "write-only" object that can only emit, since it was not given a server to attach to).

When you emit from the external script, the script will post a message to the message queue, which will be picked up by the server and then carried out.

Upvotes: 2

Related Questions