简体   繁体   中英

How do I display data from mongodb to a flask template using flask_pymongo?

Sorry if this question is a bit vague. I would like to display data from mongodb to a flask template, but I'm having troubles. This is what I have at this moment, but as you can see, it doesn't work. (I tried to be creative)

@app.route('/find')
def find():
    collection = db.lists.find()
    names = []
    
    for data in collection:
        names.append(data['name'])

    return render_template("find.html", title="Find - Website", name=names)

I know that there has to be a better way to do it, and I would really appreciate it if somebody could show me. Thanks!!

Not fully sure what is the end goal. However this is something I have used in couple of my projects before.If you want to show a table output with columns you can maybe leverage pandas and the pandas.to_html function. Something like below - I havent tested the syntax though - please do check from your end

`df = pd.DataFrame.from_dict(json_normalize(db.lists.find))
 return render_template("find.html", title="Find - Website", tables = [df.to_html(classes='dfstyle',header='true')]`

you might have to import packages like jsonify from flask, pandas and pandas.io.json.json_normalize from python

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