Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate dynamic urls in flask?

Tags:

python

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?

like image 556
I Love Python Avatar asked Jan 30 '16 22:01

I Love Python


People also ask

What is dynamic URL in Flask?

The url_for() function is used to build a URL to the specific function dynamically. The first argument is the name of the specified function, and then we can pass any number of keyword argument corresponding to the variable part of the URL.

What is the use of url_for in Flask?

The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL.


1 Answers

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 
like image 139
ATLUS Avatar answered Sep 24 '22 04:09

ATLUS