我用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的初学者,如果我犯了任何错误并帮助我解决这个问题,请放轻松。谢谢。
我通过以下方式解决了这个问题:1。导入from bson.objectid import ObjectId
2.改变路线:
# Single Article
@app.route('/home/<string:id>/', methods=['GET','POST'])
def post(id):
# Create Mongo Connection
user = mongo.db.articles
# execute query
article = user.find_one({"_id": ObjectId(id)})
return render_template("post.html", article=article)