尝试使用 Pymongo 解析从 MongoDB 到 JSON 的数据,然后 return DOM 中的列表

Trying to parse data from MongoDB to JSON using Pymongo, and then return a list in the DOM

我是 Python 和 Flask 的新手。这本质上是一个学生数据库。每个文档包含 first_namelast_namestudent_idmajor。我希望在访问 /view-students 时显示列表。代码:

@app.route("/view-students")
def view_students():
    if 'username' not in session:
        return render_template('index.html')

    students = mongo.db.students
    for student in students.find():
        student = dumps(student)
        print(student)
    return render_template('view-students.html', student=student)

这作为字符串返回,或者从谷歌搜索似乎显示的内容,BSON:

{"last_name": "Down", "student_id": "u6003698", "first_name": "Alec", "_id": {"$oid": "5ae0f4ca78ba1481a6284e83"}, "major": "German Literature"}
{"last_name": "Doe", "student_id": "u0000000", "first_name": "John", "_id": {"$oid": "5ae0f4f178ba1481a6284e84"}, "major": "Electrical Engineering"}

在客户端,我基本上想做这样的事情:

  <table class="table">
    <thead>
      <tr>
        <th scope="col">Student ID</th>
        <th scope="col">Name</th>
        <th scope="col">Major</th>
    </thead>
    <tbody>
      {% for student in students %}
      <tr>
        {{students.first_name}}
      </tr>
      {% endfor %}
    </tbody>
  </table>

我试过使用 jsonify、json 转储、json-utils,所有这些似乎要么给我一个字符串,要么告诉我它不能被序列化。

如有任何帮助,我们将不胜感激。

你必须传递一个列表作为参数,不需要转储内容:

@app.route("/view-students")
def view_students():
    if 'username' not in session:
        return render_template('index.html')

    students = list(mongo.db.students.find())
    return render_template('view-students.html', students=students)

并使用 student 而不是 students 迭代模板(注意 s):

  <table class="table">
    <thead>
      <tr>
        <th scope="col">Student ID</th>
        <th scope="col">Name</th>
        <th scope="col">Major</th>
    </thead>
    <tbody>
      {% for student in students %}
      <tr>
        {{student.first_name}}
      </tr>
      {% endfor %}
    </tbody>
  </table>