如何在烧瓶中生成动态网址?

时间:2016-01-30 22:19:40

标签: python flask

我在数据库中有几条记录,我想形成这样的URL:

mysite.com/post/todays-post-will-be-about

todays-post-will-be-about将从数据库中提取。

有什么方法可以把它从烧瓶中取出来吗?

4 个答案:

答案 0 :(得分:14)

您可以在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时,&#39; anything_here&#39;将进入您的功能并在必要时进行评估。您可能还想设置404页面处理,以防有人试图手动输入帖子:

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html', pic=pic), 404

答案 1 :(得分:8)

使用@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

答案 2 :(得分:3)

Flask路线可以包含here所示的参数:

@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

如何从数据库中获取帖子以及如何从中做出回应取决于您。

答案 3 :(得分:0)

我建议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