简体   繁体   English

使用 pyMongo 获取 Flask 中的 MongoDB 数据

[英]Fetching MongoDB data in Flask using pyMongo

I need help with fetching data from a MongoDB collection in a simple Flask webpage.我需要帮助从一个简单的 Flask 网页中的 MongoDB 集合中获取数据。 I've been trying to figure out how to fetch it but it has been of no help.我一直在试图弄清楚如何获取它,但它没有任何帮助。 My JSON data is an array of documents with 3 nested fields and I have attached it with the question.我的 JSON 数据是一个包含 3 个嵌套字段的文档数组,我已将其附在问题中。 I'm trying to fetch all the data of the JSON template at first but I've been unable to.我一开始试图获取 JSON 模板的所有数据,但我一直无法。 Once I know, I'll fetch the individual array.一旦我知道,我将获取单个数组。

Here is my Flask code:这是我的 Flask 代码:

from flask import Flask
from pymongo import MongoClient

app = Flask(__name__)

client = MongoClient("mongodb://localhost:27017/")
db = client.Learning
todos = db.data


@app.route('/')
def lists():
    for x in todos.find():
        y = print(x)
    return ""


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

And this is my data structure for the MongoDB data:这是我的 MongoDB 数据的数据结构:

在此处输入图像描述

Any help or hint will be really appreciated so I can know how to fetch the data.任何帮助或提示将不胜感激,因此我可以知道如何获取数据。 Do I have to use HTML?我必须使用 HTML 吗? If so, how can I fetch the arrays within arrays with HTML?如果是这样,我如何使用 HTML 在 arrays 中获取 arrays?

You could try using Flask-PyMongo.您可以尝试使用 Flask-PyMongo。

It works like this:它是这样工作的:

from flask import Flask
from flask_pymongo import PyMongo
from flask.json import jsonify

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/Learning"
mongo = PyMongo(app)


@app.route("/")
def lists():
    print([i for x in mongo.db.data.find({})])
    return jsonify([i for i in mongo.db.data.find({})])



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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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