0
0
Flaskframework~10 mins

Error handling in production 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 function used to render templates for error pages.

Flask
from flask import Flask, [1]
Drag options to blanks, or click blank then click option'
Aerrorhandler
Babort
Crequest
Drender_template
Attempts:
3 left
💡 Hint
Common Mistakes
Importing 'errorhandler', which cannot be directly imported from Flask.
Importing 'abort' instead of 'render_template'.
2fill in blank
medium

Complete the code to create a custom 404 error handler function.

Flask
@app.[1](404)
def not_found(error):
    return 'Page not found', 404
Drag options to blanks, or click blank then click option'
Aerrorhandler
Broute
Cbefore_request
Dafter_request
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.route instead of @app.errorhandler.
Using request lifecycle decorators like before_request.
3fill in blank
hard

Fix the error in the code to return a custom HTML template for 500 errors.

Flask
@app.errorhandler(500)
def server_error(error):
    return [1]('500.html'), 500
Drag options to blanks, or click blank then click option'
Aredirect
Brender_template
Cabort
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using abort instead of render_template.
Trying to redirect instead of rendering a page.
4fill in blank
hard

Fill both blanks to log errors and return a JSON response in production.

Flask
import logging

@app.errorhandler(500)
def internal_error(error):
    app.logger.[1]('Server Error: %s', error)
    return {'error': 'Internal Server Error'}, [2]
Drag options to blanks, or click blank then click option'
Aerror
B500
Cwarning
D404
Attempts:
3 left
💡 Hint
Common Mistakes
Logging with 'warning' instead of 'error'.
Returning wrong HTTP status code like 404.
5fill in blank
hard

Fill all three blanks to create a custom error handler that logs, renders a template, and returns the correct status code.

Flask
import logging

@app.errorhandler([1])
def handle_error(error):
    app.logger.[2]('Error occurred: %s', error)
    return [3]('error.html'), [1]
Drag options to blanks, or click blank then click option'
A404
Berror
Crender_template
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up error codes 404 and 500.
Using wrong logging level or function to render template.