尝试使用Pymongo将数据从MongoDB解析为JSON,然后在DOM中返回一个列表

时间:2018-04-26 14:43:50

标签: python json flask pymongo bson

我是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)

这会以字符串形式返回,或者从google搜索中显示,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,所有这些似乎只是给我一个字符串或者告诉我它不能被序列化。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

@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>