Python Flask Basics Templates and Static Files Flat HTML

Anders Axelsen
Anders Axelsen
3,384 Points

Is there a special way to rendering of add.html?

I only have access to the route, /, and the def index(name="Anders"): function.

The route, /add/, only displays Not Found in browser.

#simple_app.py
from flask import Flask
from flask import render_template

app = Flask(__name__)


@app.route('/')
@app.route('/<name>')
def index(name="Anders"):
    return "Hello {}".format(name)

@app.route('/add/<int:num1>/<int:num2>')
@app.route('/add/<float:num1>/<float:num2>')
@app.route('/add/<int:num1>/<float:num2>')
@app.route('/add/<float:num1>/<int:num2>')
def add(num1, num2):
    return render_template("add.html")

app.run(debug=True, port=8000, host='0.0.0.0')
#add.html
<!doctype html>
<html>
    <head>
        <title>Adding!</title>
    </head>
    <body>
        <h1>Num1 + num2 = Sum-thing!</h1>
    </body>
</html>

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,947 Points

Correct. Because there isn't an explicit @app.route('/add/'), going to that URL will not match. By adding this route, the function add() will be run. But this will bring up another error. Do you see it?

If the function add() is reached through the route '/add/' then the parameters num1 and num2 will not be defined. One fix would be to add default parameter values for num1 and num2 in the add() function signature definition.

Post back if you need more help. Good luck!!!

Anders Axelsen
Anders Axelsen
3,384 Points

Thanks Chris.

My add code with concepts from your revision:

@app.route('/add/')
@app.route('/add/<int:num1>/<int:num2>')
@app.route('/add/<float:num1>/<float:num2>')
@app.route('/add/<int:num1>/<float:num2>')
@app.route('/add/<float:num1>/<int:num2>')
def add(num1='a', num2='b'):
    return render_template("add.html")

app.run(debug=True, port=8000, host='0.0.0.0')

I see this error, jinja2.exceptions.TemplateNotFound, running the code above.

The error is unexpected for me, since my code is, seemingly, identical to the one of Kenneth.

Cheers!

Anders Axelsen
Anders Axelsen
3,384 Points

Solved it by.... watching the entire video.. =) ~ Perks of gradual procedure.

def add(num1, num2):
    context = {'num1': num1, 'num2': num2}
    return render_template("add.html", **context)
    <body>
        <h1>{{ num1 }} + {{ num2 }} = {{num1 + num2}}!</h1>
    </body>