Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,167 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.