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

I L*_*hon 12 python flask

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

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

todays-post-will-be-about会从数据库中拉出.

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

ATL*_*LUS 20

您可以在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)
Run Code Online (Sandbox Code Playgroud)

要使您的数据库信息显示在您的站点上,您需要将参数传递到模板中.因此,在您的模板中,您将引用以下参数:

<td>Post Author: {{ para1.author }}</td>
<td>Post Body: {{ para1.body }}</td>
<td>Date Posted: [{{ para2 }}] times</td>
Run Code Online (Sandbox Code Playgroud)

然后,当您访问mysite.com/post/anything_here时,'anything_here'将进入您的函数并根据需要进行评估.您可能还想设置404页面处理,以防有人试图手动输入帖子:

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html', pic=pic), 404
Run Code Online (Sandbox Code Playgroud)


sis*_*red 9

使用@app.route如下所示的装饰器:

@app.route('/post/<post_title>')
def show_post(post_title):
    #use post title to fetch the record from db
Run Code Online (Sandbox Code Playgroud)

路由部分提供了更多示例:http: //flask.pocoo.org/docs/0.10/quickstart/#routing


Wom*_*atz 5

瓶路线可以有参数显示在这里

@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
Run Code Online (Sandbox Code Playgroud)

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