Search code examples
pythonflaskblinker

Python - Can I use blinker library for this purpose?


I'm wondering if I can do these jobs with blinker library(or maybe with whatever libraries).

  1. I run a web application using Flask and within this application(maybe app.py), I define a signal named updated(e.g. blinker.signal('updated')).
  2. In a separate process, I connect(subscribe) any function(I'll call it subscriber) to the updated signal. And this process runs forever like a daemon.
  3. Whenever an update occurs on the web side, I want the subscriber function to be called.

So I wrote some codes:

app.py (Flask application)

from flask import Flask
from blinker import signal

app = Flask(__name__)
updated = signal('updated')

@app.route('/update')
def update():
    updated.send('nothing')
    return 'Updated!'

background.py

import time

from app import updated

@updated.connect
def subscriber(*args, **kwargs):
    print('An update occurred on the web side!')

while True:
    print('Waiting for signals...')
    time.sleep(1)

And ran the web application with flask run command. Now when I visit localhost:5000/update, I can see Updated! message in browser but I can't see the message An update occurred on the web side! from other process.

Is my approach wrong? If it is, how can I do such jobs? Waiting for your answers, thanks.


Solution

  • Blinker's description is:

    A fast Python in-process signal/event dispatching system.

    Emphasis mine, so no you can't use the library to send signals between two processes.

    What can you do instead? Well, the Python Standard Library's documentation has a whole chapter on Interprocess Communication and Networking. It's not clear what you're trying to build, but if you need to build a task queue (with "workers"), for instance, try Celery or TaskTiger. If you do need to actually send messages between processes, something more complex like ZeroMQ would be appropriate.