Parse URL Parameters in Flask


The request object in Flask stores any parsed URL parameters in request.args.

For example: http://localhost/users/login?next=%2Fprofile

👇

from urllib.parse import urlparse
from flask import request, current_app, abort

@users_blueprint.route('/login')
def login():

    ...

    # Redirect the user to the specified URL after login
    if 'next' in request.args:
        next_url = request.args.get('next')

        # Only accept relative URLs
        if urlparse(next_url).scheme != '' or urlparse(next_url).netloc != '':
            current_app.logger.info(f'Invalid next path in login request: {next_url}')
            return abort(400)

        current_app.logger.info(f'Redirecting after valid login to: {next_url}')
        return '<p>User logged in!</p>'

Be careful to avoid URLs when parsing user inputs: http://localhost/login?next=http://givemeyourcreditcard.com.