You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask对接MongoDB后页面刷新时MongoDB数据消失应如何解决?

问题原因

  • pymongo的find()方法返回的是游标对象,该对象本质是迭代器,仅支持一次性遍历:你当前将cursor = dbcol.find({})定义为全局变量,首次加载页面时遍历完游标后,指针会停在数据集末尾,后续刷新页面复用该游标时自然无法读取到任何数据。
  • 额外逻辑问题:app.run(debug=True)的放置位置错误,应该放在所有路由、配置代码的末尾,否则直接运行脚本启动服务时会出现逻辑加载异常。

修复方案

将MongoDB查询逻辑移到market_page路由函数内部,每次请求都重新执行查询获取新的游标,同时调整app.run的放置位置,修改后的app.py代码如下:

from flask import Flask, render_template
import pymongo

app = Flask(__name__)

@app.route('/')
@app.route('/home')
def home_page():
    return render_template("home.html")

# 数据库连接可以保留为全局,不需要每次请求重复创建连接
client = pymongo.MongoClient("localhost", 27017)
db = client.Marketplace
dbcol = db.items

@app.route('/market')
def market_page():
    # 每次请求都重新执行查询,获取全新的可用游标
    cursor = dbcol.find({})
    return render_template('market.html', items = cursor)

# app.run放在所有代码末尾,添加入口判断兼容两种启动方式
if __name__ == "__main__":
    app.run(debug=True)

你提到的form=false属于信息偏差,该参数和你遇到的问题无关,按上述方案调整后即可解决刷新数据消失的问题。

内容的提问来源于stack exchange,提问作者MadVags

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:15:03