首页 > 解决方案 > 使用 Flask, pymongo, cursor id 已经在使用中

问题描述

我正在使用“watch”来监控 Flask 应用程序中的数据库更改(pymongo 3.12.0)。我正在尝试将数据库更改推送到客户端,但是当数据库更改发生时,我收到错误:

cursor id CURSOR_ID_NUMBER is already in use

在烧瓶之外,在 python3.8 中观察流工作正常,没有超时问题或任何东西,只有在 Flask 中使用时才会发生错误。我读到它可能与服务器破坏会话有关(但如果会话被破坏,游标 ID 怎么能被使用?),但我仍然不确定如何处理它,欢迎任何建议。

在烧瓶中我有

app = Flask(__name__)
client = MongoClient(mongo_url)
db_stream = client[DB_NAME][COLLECTION_NAME].watch([{ "$match": {'fullDocument.user_id':'{}'.format(CLIENT_ID)}}])

和:

def event_stream():
    change = False 
    try:
        change = next(db_stream)
    except Exception as e:
        print("change err: {}".format(str(e)))
    print("db change: {}".format(change))
    yield dumps(change)


@app.route('/stream')
def stream():
    db_change = event_stream()
    return Response('data: {}\n\n'.format(dumps(db_change)),
                          mimetype="text/event-stream")

 在客户端:

var source = new EventSource('/stream');
source.onmessage = function (event) {
   console.log(event.data);
};

 

标签: pythonflaskpymongo

解决方案


推荐阅读