From e53c690865ade47ed05f00734ded400ed4d730d9 Mon Sep 17 00:00:00 2001 From: Rmarieta Date: Fri, 12 Jan 2024 16:54:31 +0100 Subject: [PATCH] Small modifs --- README.md | 2 +- flask/app/__init__.py | 2 +- flask/app/views/sockets.py | 24 ++++++++++++++++++++++-- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b27b26d..733d61c 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ The backend consists in: - A PostgreSQL database. - An Nginx load balancer. -- Flask containers running behind the load balancer and served over Gunicorn. +- Flask containers running behind the load balancer and served over Gunicorn to enable multi-threading. - A Redis container to coordinate websocket connections/messages while having multiple Flask processes running at the same time. To start the development containers : diff --git a/flask/app/__init__.py b/flask/app/__init__.py index 7897031..64facd3 100644 --- a/flask/app/__init__.py +++ b/flask/app/__init__.py @@ -25,7 +25,7 @@ def create_app(): app.config['SECRET_KEY'] = os.environ['SECRET_KEY'] db.init_app(app) - socketio.init_app(app, message_queue='redis://redis') + socketio.init_app(app, message_queue=os.environ.get('REDIS_MESSAGE_QUEUE_URL')) # importing and registering routes with their url prefix from .views.main import main_bp diff --git a/flask/app/views/sockets.py b/flask/app/views/sockets.py index 05119ad..f691308 100644 --- a/flask/app/views/sockets.py +++ b/flask/app/views/sockets.py @@ -1,5 +1,6 @@ -from flask_socketio import emit, send +from flask_socketio import emit, send, join_room, leave_room from app import socketio +import os @socketio.on('message') def handle_message(message): @@ -12,4 +13,23 @@ def handle_json(json): @socketio.on('my event') def handle_my_custom_event(json): - print('received my_event: ' + str(json)) \ No newline at end of file + print('received my_event: ' + str(json)) + +@socketio.on('chat') +def chat(data): + print("chat "+str(data)) + emit('chat', "From hostname " + os.uname().nodename + " : " + data['message'], broadcast=True, to=data['room']) + +@socketio.on('join') +def on_join(data): + username = data['username'] + room = data['room'] + join_room(room) + send("From hostname " + os.uname().nodename + " : " + username + ' has entered the room.', to=room) + +@socketio.on('leave') +def on_leave(data): + username = data['username'] + room = data['room'] + leave_room(room) + send("From hostname " + os.uname().nodename + " : " + username + ' has left the room.', to=room) \ No newline at end of file