0
0
Flaskframework~10 mins

Before_request hooks 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 register a function that runs before each request in Flask.

Flask
from flask import Flask
app = Flask(__name__)

@app.[1]
def before():
    print("This runs before each request")
Drag options to blanks, or click blank then click option'
Abefore_request
Broute
Cteardown_request
Dafter_request
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.route instead of @app.before_request
Using @app.after_request which runs after requests
2fill in blank
medium

Complete the code to abort the request with a 403 error inside a before_request function.

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

@app.before_request
def check():
    if not authorized():
        [1](403)
Drag options to blanks, or click blank then click option'
Aredirect
Babort
Craise
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using return 403 which does not stop the request properly
Using raise without an exception
3fill in blank
hard

Fix the error in the before_request function to correctly access the request path.

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

@app.before_request
def log_path():
    print("Request path:", request.[1])
Drag options to blanks, or click blank then click option'
Apath
Burl
Cfull_path
Dendpoint
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.url which includes the full URL
Using request.endpoint which is the function name
4fill in blank
hard

Fill both blanks to create a before_request function that sets a global variable and checks a header.

Flask
from flask import Flask, g, request, abort
app = Flask(__name__)

@app.before_request
def before():
    g.user = request.headers.get([1])
    if g.user is None:
        [2](401)
Drag options to blanks, or click blank then click option'
A"X-User"
Babort
C"Authorization"
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of abort to stop the request
Using wrong header names
5fill in blank
hard

Fill all three blanks to create a before_request hook that logs the method, path, and aborts if method is POST.

Flask
from flask import Flask, request, abort
app = Flask(__name__)

@app.before_request
def check_post():
    print("Method:", request.[1])
    print("Path:", request.[2])
    if request.method == [3]:
        abort(405)
Drag options to blanks, or click blank then click option'
Amethod
Bpath
C"POST"
D"GET"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'GET' instead of 'POST' to check method
Using request.url instead of request.path