【问题标题】:Rendering logs from Mongodb into flask route将来自 Mongodb 的日志渲染到烧瓶路由中
【发布时间】:2019-12-20 02:29:54
【问题描述】:
client = MongoClient("mongodb:xxxx")
db = client.databasename
collection = db.logs    

@app.route('/log')
def Results():
    try:
        loggings = db.collection.find()
        return render_template('index.html', loggings=loggings)
    except Exception as e:
        return dumps({'error': str(e)})

if __name__ == '__main__':  
   app.run(debug = True)

这是我的 app.py 和 'index.html' 的代码,我的代码看起来像

<!doctype html>
<html>
    <body>
        {% for message in logs %}
            <h3>{{message}}</h3>
        {%endfor%}
    </body>
</html>

当我运行代码时,它不会在 localhost:xxxx/log 路由上显示任何内容。

我可以知道为什么吗? 谢谢!

【问题讨论】:

  • 您以loggings= 发送数据,因此在模板中您必须使用... in loggings,而不是...in log

标签: python mongodb logging flask


【解决方案1】:

如果你在

中使用loggings=
render_template('index.html', loggings=loggings)

那么你必须在模板中也使用loggings

{% for message in loggings %}

但你使用{% ... in logs %}

【讨论】:

  • 非常感谢,现在我显示了日志但根本没有格式化。我可以知道是否有任何方法可以使用“表格”来格式化它们?或者任何其他方式来很好地格式化它们?非常感谢!
  • 你有你的模板 - 如果消息有很多字段,那么单独显示每个字段 - 即。 {{ message.id }}{{ message["id"] }} 。然后您可以使用CSS 将其放入不同的标签和样式HTML。如果您在消息中有字符串,那么您可以在发送到 template 之前在 Results() 中编辑它们
  • 非常感谢您的回复。我正在尝试创建一个表。那么,每一行/列的内容会是 loggings.id 还是 message.id?我是否以正确的方式接近桌子?
  • 我不知道您在数据库中有哪些列,但如果您有列,即。 idtext 然后message.id 将给出来自列id 的行中的单元格,message.text 将给出来自列text 的单元格等,所以您可以执行&lt;tr&gt;&lt;td&gt;{{ message.id }}&lt;/td&gt;&lt;td&gt;{{ message.text }}&lt;/td&gt;&lt;/tr&gt;&lt;table&gt; 中创建行
  • 所以我需要保留我在问题中发布的原始 index.html 吗?如果是,表格 () 部分应该放在哪里?而且我有成千上万的日志.. 如果没有任何其他特殊格式,它仍然适合表格格式吗?谢谢!
猜你喜欢
  • 2023-04-07
  • 2014-07-17
  • 2017-07-25
  • 1970-01-01
  • 2022-01-23
  • 2020-10-18
  • 2018-03-25
  • 1970-01-01
  • 2020-05-02
相关资源
最近更新 更多