How to generate dynamic urls in flask?

前端 未结 4 1026
长情又很酷
长情又很酷 2020-12-16 11:29

I have several records in the database which I Want to form URLs like so:

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

The todays-post-will-b

4条回答
  •  不知归路
    2020-12-16 12:05

    You can put variable names in your views.py functions. For example:

    # you can also use a particular data type such as int,str
    # @app.route('post/', methods=['GET', 'POST'])
    @app.route('post/', methods=['GET'])
    def daily_post(variable):
        #do your code here
        return render_template("template.html",para1=meter1, para2=meter2)
    

    To get your database information to display on your site, you'll want to pass parameters into the template. So, in your template you'll reference those parameters like:

    Post Author: {{ para1.author }}
    Post Body: {{ para1.body }}
    Date Posted: [{{ para2 }}] times
    

    Then when you visit mysite.com/post/anything_here, the 'anything_here' will go into your function and be evaluated as necessary. You'll probably also want to set up 404 page handling, in case someone tries to enter a post manually:

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

提交回复
热议问题