0
0
Flaskframework~10 mins

Error handler decorators 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 create an error handler for 404 errors in Flask.

Flask
from flask import Flask, render_template
app = Flask(__name__)

@app.errorhandler([1])
def not_found_error(error):
    return render_template('404.html'), 404
Drag options to blanks, or click blank then click option'
A500
B404
C403
D400
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong error code like 500 or 403.
Forgetting to use the @app.errorhandler decorator.
2fill in blank
medium

Complete the code to handle 500 Internal Server Error using a decorator.

Flask
from flask import Flask, render_template
app = Flask(__name__)

@app.errorhandler([1])
def internal_error(error):
    return render_template('500.html'), 500
Drag options to blanks, or click blank then click option'
A403
B404
C500
D400
Attempts:
3 left
💡 Hint
Common Mistakes
Using 404 instead of 500.
Not returning the correct status code with the response.
3fill in blank
hard

Fix the error in the code to correctly register a handler for 403 Forbidden errors.

Flask
from flask import Flask, render_template
app = Flask(__name__)

@app.errorhandler([1])
def forbidden_error(error):
    return render_template('403.html'), 403
Drag options to blanks, or click blank then click option'
A403
Berror403
CForbidden
D'403'
Attempts:
3 left
💡 Hint
Common Mistakes
Using quotes around the number.
Using a string or variable name instead of the code.
4fill in blank
hard

Fill both blanks to create a handler for 400 Bad Request errors that returns a JSON response.

Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.errorhandler([1])
def bad_request(error):
    response = jsonify({'error': 'Bad Request'})
    response.status_code = [2]
    return response
Drag options to blanks, or click blank then click option'
A400
B404
C500
D403
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching the decorator code and status code.
Using codes for other errors like 404 or 500.
5fill in blank
hard

Fill both blanks to create a custom error handler for 401 Unauthorized errors that returns a JSON message.

Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.errorhandler([1])
def unauthorized(error):
    response = jsonify({'message': 'Unauthorized access'})
    response.status_code = [2]
    return response
Drag options to blanks, or click blank then click option'
A401
B403
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using 403 Forbidden instead of 401.
Mismatching decorator and status code.