Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the Flask class.
Flask
from flask import [1] app = [1](__name__)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of Flask
Using jsonify as the app class
✗ Incorrect
The Flask class is imported to create the app instance.
2fill in blank
mediumComplete the code to define a route that returns a simple message.
Flask
@app.route('/') def home(): return [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning unquoted text
Returning a function call instead of string
✗ Incorrect
The return value must be a string, so it needs quotes.
3fill in blank
hardFix the error in the code to handle a 404 error with a custom message.
Flask
@app.errorhandler([1]) def not_found(error): return 'Page not found', 404
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 500 for server error instead of 404
Using 403 for forbidden
✗ Incorrect
404 is the HTTP status code for 'Not Found'.
4fill in blank
hardFill in the blank to create a route that raises a 404 error manually.
Flask
from flask import abort @app.route('/secret') def secret(): [1](404) return 'This is a secret page.'
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using raise instead of abort
Using return to send error code
✗ Incorrect
The abort function is used to raise HTTP errors in Flask.
5fill in blank
hardFill all three blanks to handle errors and return JSON with error info.
Flask
from flask import jsonify @app.errorhandler([1]) def handle_error(error): response = jsonify({'error': str(error)}) response.status_code = [2] return [3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Hardcoding status code incorrectly
Returning error instead of response
✗ Incorrect
The handler catches 404 errors, sets the response code from error.code, and returns the response object.