python - 使用 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);
};
解决方案
推荐阅读
- python - Dockerizing Scrapy - scrapy 入口点未接收命令参数
- azure - LogicApps outlook.com 连接器 GetEmails 触发器 - 获取最旧的电子邮件
- timer - 在 scheduleTimer 中使用 Unresolved Identifer
- c++ - 如何向基类添加另一个初始化函数但不编辑基文件?
- c# - 如何在同一个句子中从 Datatable 中读取多个单元格值?
- python - 如何在小部件上放置文本
- c - Sscanf - 从文件中读取所有数字 - C
- python - TypeError:预期的字符串或类似字节的对象;
- c - 用于探索矩阵的递归函数的最小参数数
- java - 每个 Java 非 void 方法都必须返回值