0
0
Flaskframework~5 mins

Redis as message broker in Flask

Choose your learning style9 modes available
Introduction

Redis as a message broker helps different parts of your app talk to each other by sending messages quickly and simply.

You want to send notifications between different parts of your Flask app.
You need to handle tasks in the background without making users wait.
You want to connect multiple services that work together in your app.
You want to build a chat app where messages go instantly between users.
Syntax
Flask
import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.publish('channel_name', 'your message')

pubsub = r.pubsub()
pubsub.subscribe('channel_name')
for message in pubsub.listen():
    print(message)

Use publish to send messages to a channel.

Use subscribe and listen to receive messages from a channel.

Examples
Sends the message 'Hello subscribers!' to the 'news' channel.
Flask
r.publish('news', 'Hello subscribers!')
Listens for messages on the 'news' channel and prints them as they arrive.
Flask
pubsub = r.pubsub()
pubsub.subscribe('news')
for msg in pubsub.listen():
    print(msg)
Sample Program

This Flask app lets you send messages to a Redis channel called 'chat' via a POST request to '/send'. A background thread listens and prints messages received on that channel.

Flask
from flask import Flask, request
import redis
import threading

app = Flask(__name__)
r = redis.Redis(host='localhost', port=6379, db=0)

# Background thread to listen for messages

def listen_messages():
    pubsub = r.pubsub()
    pubsub.subscribe('chat')
    for message in pubsub.listen():
        if message['type'] == 'message':
            print(f"Received: {message['data'].decode()}")

listener_thread = threading.Thread(target=listen_messages, daemon=True)
listener_thread.start()

@app.route('/send', methods=['POST'])
def send_message():
    msg = request.form.get('message', '')
    if msg:
        r.publish('chat', msg)
        return 'Message sent!'
    return 'No message provided', 400

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Make sure Redis server is running before starting your Flask app.

Use background threads or separate processes to listen for messages without blocking your app.

Decode message data from bytes to string when receiving messages.

Summary

Redis can send and receive messages between parts of your Flask app.

Use publish to send and subscribe with listen to receive.

Background threads help listen for messages without stopping your app.