SocketIO 没有使用 Flask 向前端发出新的传入数据 frrom mongo

SocketIO is not emitting new incoming data frrom mongo to frontend using Flask

提问人:James 提问时间:11/15/2023 最后编辑:James 更新时间:11/15/2023 访问量:17

问:

我的代码利用Change Streams来检测MongoDB中任何新插入的数据。随后,它被设计为使用 SocketIO 将这些新数据发送到前端。

目前,Flask 代码可以有效地检测 MongoDB 中的更改或新数据,并且数据在终端中可见地打印出来。但是,存在检测到的数据未成功发出的问题。尽管使用发出数据的简单函数成功进行了测试,但未能发出检测到的数据的具体原因仍不清楚。

我将不胜感激任何帮助或建议,我已经花了好几天时间解决这个问题。

Flask 应用程序:

from flask import Flask, render_template
from pymongo import MongoClient
from flask_socketio import SocketIO
from flask_cors import CORS
import threading

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="http://127.0.0.1:5000")

# Replace the following line with your MongoDB Atlas connection string
client = MongoClient("mongodb+srv://code7lab:[email protected]/test?retryWrites=true&w=majority")

# Access the 'test' database using dictionary-style notation
db = client['test']

# List collections in the current database
collections = db.list_collection_names()
print(f"Collections in {db.name}: {collections}")

collection = db.coordinates

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    print('Client connected')

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

def watch_collection():
    print("Watching collection...")
    try:
        with collection.watch() as change_stream:
            for change in change_stream:
                print("Change detected:", change)

                if 'fullDocument' in change:
                    new_data = change['fullDocument']
                    new_data['_id'] = str(new_data['_id'])
                    print("New Data:", new_data)
                    socketio.emit('new_data', new_data)
                else:
                    print("Change event does not contain 'fullDocument'.")
    except Exception as e:
        print("Error in change stream:", e)

if __name__ == '__main__':
    thread = threading.Thread(target=watch_collection)
    thread.daemon = True
    thread.start()
    socketio.run(app, debug=True)

简单测试工作代码:

def emit_data():
    count = 0
    while True:
        socketio.emit('new_data', {'count': count, 'message': 'Hello from server!'})
        count += 1

if __name__ == '__main__':
    thread = threading.Thread(target=emit_data)
    thread.daemon = True
    thread.start()
    socketio.run(app, debug=True)

前端 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket.IO Example</title>
</head>
<body>
    <h1>Socket.IO Example</h1>
    <ul id="data-list"></ul>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var socket = io.connect('http://' + document.domain + ':' + location.port);

            socket.on('connect', function () {
                console.log('Connected to server');
            });

            socket.on('new_data', function (data) {
                console.log('New data received:', data);

                var dataList = document.getElementById('data-list');
                dataList.innerHTML = ''; // Clear existing list

                var listItem = document.createElement('li');
                listItem.appendChild(document.createTextNode(JSON.stringify(data)));
                dataList.appendChild(listItem);
            });

            socket.on('disconnect', function () {
                console.log('Disconnected from server');
            });
        });
    </script>
</body>
</html>

MongoDB 烧瓶 socket.io Pymongo

评论


答: 暂无答案