我在数据库中有几条记录,我想像这样形成 URL:
mysite.com/post/todays-post-will-be-about
todays-post-will-be-about
将从数据库中提取。
有什么方法可以在 flask 中完成吗?
最佳答案
您可以将变量名放在您的 views.py 函数中。例如:
# you can also use a particular data type such as int,str
# @app.route('post/<int:id>', methods=['GET', 'POST'])
@app.route('post/<variable>', methods=['GET'])
def daily_post(variable):
#do your code here
return render_template("template.html",para1=meter1, para2=meter2)
要让您的数据库信息显示在您的网站上,您需要将参数传递到模板中。因此,在您的模板中,您将引用这些参数,例如:
<td>Post Author: {{ para1.author }}</td>
<td>Post Body: {{ para1.body }}</td>
<td>Date Posted: [{{ para2 }}] times</td>
然后当您访问 mysite.com/post/anything_here 时,“anything_here”将进入您的函数并根据需要进行评估。您可能还想设置 404 页面处理,以防有人试图手动输入帖子:
@app.errorhandler(404)
def not_found_error(error):
return render_template('404.html', pic=pic), 404
关于python - 如何在 flask 中生成动态网址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35107885/