简体   繁体   中英

Display MongoDB Documents data on a Webpage using Python Flask

I wrote a code using Python and trying to display all the Documents from Mongodb on a web page. However, on webpage I see the Column names, but no data. And on the command, it does print all the data. Any help is greatly appreciated.

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)

The HTML (Results.html) Page is:

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

Removed the for loop and rewrote the code as below:

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

Documents are displayed on the HTML Page as is.

(***Will work on the formatting part. Meanwhile any pointers are greatly appreciated.)

Try using key,value function of for loop and also remove that loop in the python app file from route like upper answer @Dinakar suggested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM