Categories
Python Answers

How to create dynamic URLs in Python Flask with url_for()?

Spread the love

Sometimes, we want to create dynamic URLs in Python Flask with url_for().

In this article, we’ll look at how to create dynamic URLs in Python Flask with url_for().

How to create dynamic URLs in Python Flask with url_for()?

To create dynamic URLs in Python Flask with url_for(), we can call url_for with the name of the view function and the URL parameter values.

For instance, if we have

@app.route('/<variable>/add', methods=['GET', 'POST'])
def add(variable):
  # ...

@app.route('/<variable>/remove', methods=['GET', 'POST'])
def remove(variable):
  # ...

to add 2 view functions.

Then we can create URLs for the view functions with

url_for('add', variable=foo)
url_for('remove', variable=foo)

We call url_for with the view function name and the variable URL parameter value to return the URLs for the routes.

Conclusion

To create dynamic URLs in Python Flask with url_for(), we can call url_for with the name of the view function and the URL parameter values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *