Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Rod Rojas
Rod Rojas
1,436 Points

I don't quite understand the video explanation for name=request.args.get('name', name)

I don't quite understand the video explanation for name=request.args.get('name', name)

what is args again?

do the two arguments in the get() work as an if/else?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The flask request object contains all of the information received from the browser when it requests a page. Included in this request object is an args object that contains any query string arguments present in the URL sent by the browser.

The code

@app.route("/")
def index(name="Treehouse"):
    name = request.args.get('name', name)
    return "Hello from {}".format(name)

defines a default for name in the function definition as "Treehouse". Using the .get() method from request.args looks for the 'name' key in the query string arguments. If not found, then the default value of the variable name is used.

From the Flask API docs:

args

    A MultiDict with the parsed contents of the query string. 
    (The part in the URL after the question mark).

From the Werkzeug MulitDict docs:

get(key, default=None, type=None)

    Return the default value if the requested data doesn’t exist. If type is
    provided and is a callable it should convert the value, return it or raise
    a ValueError if that is not possible. In this case the function will return
    the default as if the value was not found:

    >>> d = TypeConversionDict(foo='42', bar='blub')
    >>> d.get('foo', type=int)
    42
    >>> d.get('bar', -1, type=int)
    -1

    Parameters: 

        key – The key to be looked up.
        default – The default value to be returned if the key can’t be looked up.
            If not further specified None is returned.
        type – A callable that is used to cast the value in the MultiDict. If a
            ValueError is raised by this callable the default value is returned.
Rod Rojas
Rod Rojas
1,436 Points

thank you Chris. I am trying to digest this.