I want to make a chat app using flask but I'm facing a problem concerning the loading of…
- User
I want to make a chat app using flask but I'm facing a problem concerning the loading of the messages: app.py :"import os import json from flask import Flask, render_template from flask_socketio import SocketIO, send
app = Flask(name) app.config['SECRET_KEY'] = 'fsht' socketio = SocketIO(app)
File path for storing messages
messages_file = 'messages.json'
Initialize messages with existing data or create a new file
if not os.path.exists(messages_file): with open(messages_file, 'w') as f: json.dump([], f)
def load_messages(): try: with open(messages_file, 'r') as f: messages = json.load(f) except json.JSONDecodeError: messages = [] return messages
def save_message(msg): messages = load_messages() messages.append(msg) with open(messages_file, 'w') as f: json.dump(messages, f)
@app.route('/') def index(): messages = load_messages() return render_template('index.html', messages=messages)
@socketio.on('message') def handle_message(msg): save_message(msg) send(msg, broadcast=True)
@socketio.on('load_messages') def handle_load_messages(): messages = load_messages() send(messages)
if name == 'main': socketio.run(app, debug=True) " index.html:"
code// Function to display a message on the chat box function displayMessage(msg) { const chatBox = document.getElementById('chat-box'); const msgElement = document.createElement('div'); msgElement.innerHTML = msg.replace(/\n/g, '<br>'); // Replace \n with <br> tags msgElement.classList.add('message'); // Add a class for styling chatBox.appendChild(msgElement); } // Function to send a message document.getElementById('send').onclick = function() { const message = document.getElementById('message').value; socket.send(message); document.getElementById('message').value = ''; }; // Event handler for receiving messages from server socket.on('message', function(msg) { displayMessage(msg); }); // Event handler for receiving initial messages from server on connect socket.on('connect', function() { socket.emit('load_messages'); }); // Event handler for loading and displaying initial messages socket.on('load_messages', function(messages) { messages.forEach(function(msg) { displayMessage(msg); }); }); </script> - Assistant