我用 python、flask、mongodb 和 bootstrap 编写了一个博客网络应用程序。在我的工作中,如果我选择一篇文章,程序必须进入数据库,找到所选文章的相应ID,并将文章的内容渲染到指定的html文件中。这是路线的代码示例:
# Home with articles displayed
@app.route('/home', methods=['GET','POST'])
def article():
# Create Mongodb connection
user = mongo.db.articles
# Execute query to fetch data
results = user.find()
# Iterate the data retrieved
if results is not None:
articles = results
return render_template("index.html", articles=articles)
else:
msg = Markup("<h3>No Articles Posted.</h3>")
return render_template("index.html", msg=msg)
# Single Article
@app.route('/home/<id>/', methods=['GET','POST'])
def post(id):
# Create Mongodb Connection
user = mongo.db.articles
# execute query
article = user.find_one({'_id': id})
return render_template("post.html", article=article)
这也是 HTML 文件的代码示例:
{% extends 'base.html' %}
{% block title %} <title>Articles | Blog</title> {% endblock %}
{% block content %}
<!-- Page Header -->
<div class= "jumbotron">
<h5>{{article.title}}</h5>
<small>Written by Mr. Boss on {{article.date}} </small>
<hr>
<p class="lead">{{article.body}}</p>
</div>
<!-- Post Content -->
{% endblock %}
当我选择文章时页面呈现正常,但问题是它没有将信息从 mongodb 呈现到 html 文件。这是json中的mongodb数据:
{
"_id": ObjectId("5c79d99195eded2364b03813"),
"title":"Article One",
"body":"This is the first article",
"date":"2019-03-02T00:00:00.000Z"
}
拜托,我是python的初学者,所以如果我犯了任何错误,请放轻松,并帮助我解决这个问题。谢谢。