Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

python - How to generate dynamic urls in flask?

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-be-about will be pulled from a Database.

Is there some way I could pull this off in flask?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/<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)

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:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...