Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Generating URLs and Handling Redirects in Flask with url_for

Tech 1

Flask provides the url_for() function to dynamically generate URLs for view functions instead of hardcoding them. This approach offers two key advantages: it avoids the need to update URLs manually across the codebase if routes change, and it automatically handles URL escaping for special characters and Unicode data.

The url_for() function takes the name of a view function as its first argument. Any additional keyword arguments correspond to route variables or are appended as query parameters.

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def index():
    # Generates: /article/1?page=1&name=1
    print(url_for('show_article', aid=1, page=1, name=1))
    return 'Hello World'

@app.route('/article/<aid>')
def show_article(aid):
    # Generates: /?next=%2F
    print(url_for('index', next='/'))
    return f'Article List {aid}'

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

When executed, accessing the root path / prints /article/1?page=1&name=1, while visiting /article/1 prints /?next=%2F, demonstrating how route parameters and query strings are handled.

Flask also supports HTTP redirects using the redirect() helper. This is commonly used to guide users to different pages—for example, redirecting unauthenticated users to a login page.

from flask import Flask, url_for, redirect, request

app = Flask(__name__)

@app.route('/login/', methods=['GET', 'POST'])
def login():
    return 'Login Page'

@app.route('/profile/', methods=['GET', 'POST'])
def user_profile():
    username = request.values.get('name')
    if not username:
        return redirect(url_for('login'))
    return username

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

Accessing /profile/ without a name parameter triggers a redirect to /login/, illustrating conditional redirection based on request data.

Tags: Flask

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.