payam payam - 1 year ago 250
Python Question

flask argument in render_template

The name as an argument to hello function is assigned None, but why the name in render_template will take the value of the name if provided in the url? Basically my question is how Python knows which name is None and which name is given in the url?

from flask import render_template
def hello(name=None):
return render_template('hello.html', name=name)

the hello.html is:

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}

Answer Source

Flask is a framework and there is a lot of code behind the scenes (especially werkzeug) which does all the request processing, then it calls your view function and then it prepares a complete response.

So the answer is, that Python does not know the URL, but Flask does and calls your view function either with the name (overwriting the default None) or without it.

The name variable of the view function is passed to the template under the same name. That are the two names in this line:

return render_template('hello.html', name=name)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download