使用Python Flask在网页上显示MongoDB文档数据

时间:2019-08-24 10:25:49

标签: python mongodb flask

我使用Python编写了代码,并尝试在网页上显示Mongodb的所有文档。但是,在网页上,我看到列名,但没有数据。 并且在命令上,它确实打印了所有数据。任何帮助将不胜感激。

import pymongo
from pymongo import MongoClient
import datetime
import sys
from flask import Flask, render_template, request
import werkzeug
from flask_table import Table,Col
from bson.json_util import dumps
import json

app = Flask(__name__)

try:
 client = pymongo.MongoClient("XXXX")
 print("Connected to Avengers MongoClient Successfully from Project 
 Script!!!")
except:
 print("Connection to MongoClient Failed!!!")

db = client.avengers_hack_db

@app.route('/')
def Results():
    try:
        Project_List_Col = db.ppm_master_db_collection.find()#.limit(10)
        for row in Project_List_Col:
        print(row)
        return render_template('Results.html',tasks=row)

    except Exception as e:
    return dumps({'error': str(e)})

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

HTML(Results.html)页面为:

<html>
  <body>
     {% for task_id in tasks %}
        <h3>{{task_id}}</h3>
     {% endfor %}
   </body>
</html>

1 个答案:

答案 0 :(得分:0)

删除了for循环并重新编写了如下代码:

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

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

文档按原样显示在HTML页面上。

(***将用于格式化部分。与此同时,任何指针都将不胜感激。)