How To Generate URL And Route Dynamically In Flask

We can set route dynamically instead of fixed route.

For example In the pre-determined route links generate like this example.com/users/profile

In the dynamically gendered route will be like this  example.com/users/custom_profile_name


We will use

@app.route('/<username>')

The code will be like this

@app.route('/<username>')
def show_profile(username):
    return username

We can use anything in the <username> here

So if we  load page like example.com/anything_here

It will show the route. This is the complete example. Copy and try and customize the code by yourself.



from flask import Flask, url_for

app = Flask(__name__)

@app.route('/<username>')
def show_profile(username):
    return username

@app.route('/')
def index():
    example_link = url_for('show_profile', username='example')
    return f"You are on index route. Go to <a href='{example_link}'>/example</a> for an example."

if __name__ == '__main__':
    app.run(debug=True)

  
  

Related Posts

Flask session simplest example
July 3, 2024

Flask sessions are useful when we want to remember a specific user. For example to know the user already visited the website before. So we can generate dynamic content for that user. Or we can use login based system In this code we will use the simplest flask session example Run the code go the […]

Expiring Links Tutorial: Python Flask One-Time Link Generator
June 15, 2024

One time links are essential where users want to share resources with co-worker or friend’s effortlessly but at the same time restrict other from access. Its works best because the link automatically inactive if some one go to the link for the first time. That means the same link will not work for the second […]

Create your first chat application with Flask and Socketio
April 27, 2024

We will use socketio for real-time messaging First install our dependency for this application pip install flask pip install flask-socketio Copy Code How it will work. Every user will get an unique key. If the the other user submit the other users key that will send the message. its like sending message to unique username […]