Flask+MongoDB+HTMX项目:如何仅展示字典指定值?
解决方案
1. 修改Flask路由代码
当前路由返回完整的MongoDB文档数组,导致页面渲染整个JSON结构。需要调整路由,仅返回count_testing的数值:
@app.route('/data') def get_data(): # 获取目标文档(如需指定特定文档,可在find_one中添加查询条件,如find_one({"_id": ObjectId("xxx")})) target_doc = collection.find_one() # 提取count_testing的值,字段不存在时返回默认值0 return str(target_doc.get('count_testing', 0))
2. 保持HTML代码不变
你的HTMX配置已满足需求,无需修改:
<h1>MongoDB Data Test</h1> <div id="data-container" hx-get="/data" hx-trigger="load, every 3s" hx-target="#data-container" hx-swap="innerHTML"> <!-- Data will be injected here --> <span></span> </div>
说明
- 用
find_one()替代find(),直接获取单个目标文档(若需处理多个文档的count_testing,可遍历结果后拼接数值或计算总和再返回) - 通过
target_doc.get('count_testing', 0)安全提取字段,避免字段不存在时抛出异常 - 路由返回纯文本格式的数值,HTMX会直接将其替换到容器中,页面仅显示所需数字
内容的提问来源于stack exchange,提问作者user26831591
相关产品推荐
相关产品推荐

