0
0
Flaskframework~10 mins

Exception handling in routes in Flask - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Flask class.

Flask
from flask import [1]
Drag options to blanks, or click blank then click option'
Arequest
BFlask
Crender_template
Djsonify
Attempts:
3 left
💡 Hint
Common Mistakes
Importing request instead of Flask
Using jsonify which is for JSON responses
Importing render_template which is for HTML templates
2fill in blank
medium

Complete the code to define a route that handles GET requests at '/' path.

Flask
@app.route('[1]', methods=['GET'])
def home():
    return 'Hello World!'
Drag options to blanks, or click blank then click option'
A/
B/home
C/index
D/main
Attempts:
3 left
💡 Hint
Common Mistakes
Using '/home' or '/index' which are valid but not root
Forgetting the leading slash
3fill in blank
hard

Fix the error in the code to catch exceptions in the route.

Flask
from flask import Flask
app = Flask(__name__)

@app.route('/data')
def data():
    try:
        result = 10 / [1]
        return str(result)
    except ZeroDivisionError:
        return 'Cannot divide by zero', 400
Drag options to blanks, or click blank then click option'
A''
B0
CNone
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 causes a ZeroDivisionError
Using None or empty string causes TypeError
4fill in blank
hard

Fill both blanks to raise and catch a ValueError in the route.

Flask
@app.route('/check')
def check():
    try:
        if int('abc') [1] ValueError:
            raise ValueError('Invalid number')
    except [2] as e:
        return str(e), 400
Drag options to blanks, or click blank then click option'
A==
B!=
CValueError
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!=' in condition
Catching wrong exception type like TypeError
5fill in blank
hard

Fill all three blanks to handle a KeyError in a route and return JSON error message.

Flask
from flask import jsonify

@app.route('/item')
def item():
    data = {'name': 'apple'}
    try:
        value = data[[1]]
        return jsonify({{'value': value}})
    except [2] as e:
        return jsonify({{'error': str(e)}}), [3]
Drag options to blanks, or click blank then click option'
A'price'
BKeyError
C404
D'name'
Attempts:
3 left
💡 Hint
Common Mistakes
Using existing key 'name' so no error occurs
Catching wrong exception type
Returning wrong status code