【问题标题】:How to pass data from database to html using jinja2, Flask and mongodb and while loop如何使用 jinja2、Flask 和 mongodb 以及 while 循环将数据从数据库传递到 html
【发布时间】:2015-03-17 17:49:53
【问题描述】:

我对将数据从数据库 (mongodb) 传递到 html 感到困惑。

我在“init.py”中有 python 代码,它使用 while 逻辑查询数据库 - 请参见下面的代码 sn-p:

from pymongo import MongoClient

from flask import Flask, render_template

@app.route("/snapshot")

def pymongo_query():
   db=client.collection
   months=[1,2,3,4,5,6,7,8,9,10,11,12]
   while months:
      mon=months.pop()
      query=list(db.collection.find({args}))
      query=query[0]
      month=query['month']
      item_1=query['item_1']
      item_2=query['item_2']

此代码的作用是遍历列表中的数字表示的每个月份,并查询相应月份的数据库。我使用 while 循环持续数月。在 Python 中,我会在循环结束时使用 print 来输出结果。

如何使用 jinja2 将数据输出到 html 中?我想知道我是否需要在 jinja 中使用 while 逻辑,或者将其保留在上面的 init.py 文件中。

【问题讨论】:

    标签: mongodb python-3.x flask jinja2 pymongo


    【解决方案1】:

    希望对你有帮助。

    您可以通过将参数 item_1、item_2、month 等添加到列表或字典中来将这些参数传递给 HTMLfile。

    list=[month,item_1,item_2]
    or 
    list=[]
    
    list.append(month)
    list.append(item_1)
    list.append(item_2)
    

    并将其传递为

    @app.route('/')
    def something():
        return render_template("abc.html",my_list=list)
    

    现在在 html 中使用它(使用 jinja2) 添加一些代码,例如:

    <ul>
        {% for n in my_list %}
        <li>{{n}}</li>
        {% endfor %}
    </ul>
    

    在您的 abc.html 文件中。 现在再次运行 init.py 文件并检查输出。

    【讨论】:

      【解决方案2】:

      Like the tutorial in the Flask docs demonstrates,你返回一个对render_template的调用,将模板需要的信息传递给调用。所有应用程序和复杂逻辑都应远离模板。假设您在“templates”文件夹中创建了一个“snapshot.html”模板,并假设您在 while 循环中将item_1item_2 收集到一个集合items

      return render_template('snapshot.html', items=items)
      

      【讨论】:

        猜你喜欢
        • 2019-05-10
        • 2014-02-05
        • 1970-01-01
        • 2019-12-31
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多