我在数据库中有若干条记录,我想要形成以下链接:
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
像下面展示的一样使用@app.route
修饰器:
@app.route('/post/<post_title>')
def show_post(post_title):
#use post title to fetch the record from db
在路由部分可以找到更多的示例: http://flask.pocoo.org/docs/0.10/quickstart/#routing
Flask的路径可以像这里所示,包含参数:
@app.route("post/<identifier>")
def post(identifier): # parameter name must match dynamic route parameter name
the_post = get_from_database_by(identifier)
response = make_response_from_entity(the_post)
return response
从数据库中获取文章并制作响应的方式取决于您。
我建议使用SQLAlchemy http://flask-sqlalchemy.pocoo.org/。这是一种非常简单和快速的方法。
app.py
from flask import Flask, render_template
try:
from .alchemy import Post, db
except:
from alchemy import Post, db
app = Flask(__name__)
@app.route('/post/<url>')
def post(url):
url = Post.query.filter_by(url=url).first_or_404()
id = url.id
author = url.author
title = url.title
body = url.body
date = url.date
return render_template('post.html', title=title, id=id, author=author, body=body, date=date)
if __name__ == '__main__':
app.run(debug=True)
alchemy.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import datetime
app = Flask(__name__)
SQLALCHEMY_TRACK_MODIFICATIONS = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:pasword@localhost/base'
db = SQLAlchemy(app)
class Post(db.Model):
__tablename__ = "table"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200))
url = db.Column(db.String(220))
author= db.Column(db.String(50))
body = db.Column(db.String(50000))
date = db.Column(db.DateTime)
def __init__(self, title, url, author, body):
self.title = title
self.url = url
self.author= author
self.body = body
self.date = datetime.datetime.utcnow()
def __repr__(self):
return '<Post %r>' % self.url