Python -Flask我想以纯格式在HTML页面上显示Mongodb中存在的数据

时间:2018-11-22 06:43:07

标签: python mongodb web flask flask-restful

我在Mongodb数据库中有一个问题数据列表。我想在HTML页面上逐个问题地显示。这是我的Flask代码

from flask import Flask, render_template, request, url_for
from pymongo import MongoClient
from bson.json_util import dumps
import json

client = MongoClient('localhost:27017')
db = client.girish

app = Flask(__name__)
@app.route("/questions", methods = ['GET'])
def questions():
    try:
        names = db.questions.find({},{"ques":1,"options":1,"_id":0,"quesid":1,"ans":1}).limit(10)
        return render_template('index.html', names=names)
        #return dumps(names)
    except Exception as e:
        return dumps({'error' : str(e)})

@app.route("/answers", methods = ['POST'])
def answers():
    try:
        data = json.loads(request.data)
        quesid = data['quesid']
        yourans = data['yourans']
        if quesid and yourans:
            status = db.myanswers.insert_one({
                "quesid" : quesid,
                "yourans" : yourans
            })
        return dumps({'message' : 'SUCCESS'})
    except Exception as e:
        return dumps({'error' : str(e)})

@app.route("/myanswers", methods = ['GET'])
def myanswers():
    try:
        answers = db.myanswers.find({},{"quesid":1,"yourans":1})
        return dumps(answers)
    except Exception as e:
        return dumps({'error' : str(e)})

@app.route("/check/<id>", methods = ['GET','POST'])
def check(id):
    try:
        doc=db.questions.find({'quesid':float(id)})
        return dumps(doc)
    except Exception as e:
        return dumps({'error': str(e)})




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

我可以在HTML页面上显示monodb中存在的数据的可能方式是什么?我是python Web开发的新手。请帮助我进行详细的过程。

这是我的python mogodb注入代码

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["girish"]
mycol = mydb["questions"]

mylist = [
 {

        "ques" : "what is test?",
        "options" : [
                {
                        "op1" : "test",
                        "op2" : "test",
                        "op3" : "test"
                }
        ],
        "quesid" : 1,
        "ans" : 1
},
{

        "ques" : "what is test2?",
        "options" : [
                {
                        "op1" : "test",
                        "op2" : "test",
                        "op3" : "test"
                }
        ],
        "quesid" : 2,
        "ans" : 1
},
{

        "ques" : "what is test3?",
        "options" : [
                {
                        "op1" : "test",
                        "op2" : "test",
                        "op3" : "test"
                }
        ],
        "quesid" : 3,
        "ans" : 1
},
{

        "ques" : "what is test4?",
        "options" : [
                {
                        "op1" : "test",
                        "op2" : "test",
                        "op3" : "test"
                }
        ],
        "quesid" : 4,
        "ans" : 1
},
{

        "ques" : "what is test5?",
        "options" : [
                {
                        "op1" : "test",
                        "op2" : "test",
                        "op3" : "test"
                }
        ],
        "quesid" : 5,
        "ans" : 1
},
]

x = mycol.insert_many(mylist)

如何创建html页面以及如何与数据库链接?

1 个答案:

答案 0 :(得分:0)

如何创建HTML页面?

Flask使用称为jinja templates的东西,它具有特定的语法。它结合了HTML结构和您的数据,以返回一个HTML页面,其中填充了要在浏览器中显示的数据

如何与我的数据库链接?

我看到您正在使用PyMongo从MongoDB馈送和读取数据,这是完美的。

现在是链接部分,

创建一个python函数来访问数据库中的数据,将其放入python变量中,使用所有必需的逻辑,然后将该python变量传递给html模板。您将必须提供一个唯一的URL,Web浏览器将使用该URL使用@ app.route

来调用此功能。

我正在编写示例代码来显示questions集合中的所有问题

@app.route("/questions", methods = ['GET'])
def questions():
    try:
        questions = db.questions.find({},{"ques":1,"ans":1})
        return render_template('questions.html', questions = questions)
    except Exception as e:
        return dumps({'error' : str(e)})

现在,呈现数据的模板- Jinja 2模板提供了一种在html文件中显示python变量值的方法。 Jinja允许您使用条件语句(if-else)以及适当用例的for循环。

Questions.html

<!doctype html>
<html>
   <body>
         {% for question in questions %}
            <h3>{{question["ques"]}}</h3>
         {% endfor %}
   </body>
</html>