Python: get correct link with dynamic URLs in Flask with url_for()

Issue

I have html template, and python function(driver_links), my functional work but I have the wrong link

html template (driver_id.html):

<a href="{{ url_for('driver_links', driver_id=key[0]) }}">{{key[0]}}</a>

function:

@app.route("/report/drivers/<driver_id>")
def driver_links(driver_id):

    context = {

        "report": sort_asc_desc('data', 'asc'),
        "test": driver_id
    }
    return render_template('driver_id.html', **context)

wrong link I have: http://127.0.0.1:5000/report/drivers/SVF

if I change @app.route in function(driver_links) to:

@app.route("/report/drivers/")

I get a correct link, but function doesn’t work

example correct link: http://127.0.0.1:5000/report/drivers/?driver_id=SVF

Solution

Choose between variable rules or url parameters.
If you use the former, the required, extracted parameter is passed as a variable to the function.

@app.route("/report/drivers/<driver_id>")
def driver_links(driver_id):
    # ...

With the latter, you have to ask for the optional parameter from the dictionary request.args and no arguments are passed to the function.

from flask import request

@app.route("/report/drivers/")
def driver_links():
    driver_id = request.args.get('driver_id')
    # ...

Note that you can specify a default value and a type conversion here. You can find the documentation for this here.

Answered By – Detlef

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published