3

I have a Redis client in the cache file:

from redis import Redis

client = Redis(host='0.0.0.0', port=6379, db=0)

That I use to subscribe in the task file:

from cache import client

pubsub = client.pubsub()

def show(message):
    print(message.get('data'))

pubsub.subscribe(**{'msg': show})

Then in a Flask route in the server file I publish a message in the channel msg:

from cache import client

client.publish(
    'msg',
    '( :'
)

But when I make a request to the route, nothing is published, or it is but nothing is shown. I have already try to see the log, read the documentation, use the execute command, looked a similar example, etc, but nothing worked. Here's the code to a more detailed context. Any tips?

Obs: As you can see in the code on the Github repository, the subscribe and the publish are in different threads

  • 1
    As `subscribe` method docs says: Channels supplied as keyword arguments expect a channel name as the key and a callable as the value. A channel's callable will be invoked automatically when a message is received on that channel **rather than producing a message via listen() or get_message()`**. – bc291 Jan 03 '20 at 08:33
  • 1
    At first, to make sure core code works, please use `pubsub.subscribe('msg')`. – bc291 Jan 03 '20 at 08:35
  • 1
    Also note, that `**{'msg': show}` is equivalent of just passing kwargs as `msg=show`. – bc291 Jan 03 '20 at 08:37
  • Yes, the core code runs, if I publish at the line after the subscribe. I'm using objects because I'm gonna receive them in a request, but thanks for remember ( : –  Jan 03 '20 at 11:41
  • 1
    If it runs, that you can switch back to your old solution, but mind that `get_message` would be blocked forever. After removing it and writing whole logic in `show`, everything will work. – bc291 Jan 03 '20 at 11:43
  • No, no, I mean it runs if I place the `publish` manually after the `subscribe` declaration, but it still doesn't work on the Flask route. –  Jan 03 '20 at 12:17
  • I figured out that if I run the Flask application with the `threaded` option set to `True`, then the messages are published in the channel, through the Flask route. I'm trying to understand why it happens (the [documentation](https://werkzeug.palletsprojects.com/en/0.16.x/serving/#werkzeug.serving.run_simple) doesn't mention nothing about this behavior) and how to avoid a large amount of threads, once each request will be handle in a different thread. –  Jan 03 '20 at 12:18
  • 1
    What flask version are you running? threaded=True is default from 1.0.0 – bc291 Jan 03 '20 at 13:14
  • 1.1.1 Do you know about the behavior with `threaded = False`? –  Jan 03 '20 at 14:29
  • 1
    Yes, requests are handled one at a time if set to `False`. – bc291 Jan 03 '20 at 14:55
  • Yes, but I don't understand how it breaks the publisher... anyways, thanks ( : –  Jan 03 '20 at 15:20

0 Answers0