0
0
Flaskframework~10 mins

Before_request as middleware alternative 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'
Aroute
Bteardown_request
Cafter_request
Dbefore_request
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.route instead of @app.before_request
Using @app.after_request which runs after the request
Using @app.teardown_request which runs after response
2fill in blank
medium

Complete the code to access the current request path inside a before_request function.

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

@app.before_request
def check_path():
    path = request.[1]
    print(f"Request path is: {path}")
Drag options to blanks, or click blank then click option'
Aurl
Bmethod
Cpath
Dheaders
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.url which includes full URL
Using request.method which is HTTP method
Using request.headers which is request headers
3fill in blank
hard

Fix the error in the before_request function to correctly abort requests to '/forbidden'.

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

@app.before_request
def block_forbidden():
    if request.path == '/forbidden':
        [1](403)
Drag options to blanks, or click blank then click option'
Aabort()
Babort
Creturn abort
Dreturn abort()
Attempts:
3 left
💡 Hint
Common Mistakes
Returning abort instead of calling it
Calling abort with extra parentheses in the blank
Not calling abort at all
4fill in blank
hard

Fill both blanks to create a before_request function that sets a global variable and logs the request method.

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

@app.before_request
def setup():
    g.user = 'guest'
    print(f"Method: {request.[1]")
    g.[2] = 123
Drag options to blanks, or click blank then click option'
Amethod
Bpath
Cuser
Did
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.path instead of request.method
Using g.user again instead of a new variable
Confusing variable names in g
5fill in blank
hard

Fill all three blanks to create a before_request function that checks a header and aborts if missing.

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

@app.before_request
def check_header():
    token = request.headers.get('[1]')
    if not token:
        [2](401)
    print(f"Token: {token}")
    request.[3] = token
Drag options to blanks, or click blank then click option'
AAuthorization
Babort
Ctoken
Dheaders
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong header name
Not calling abort correctly
Assigning token to request.headers instead of request.token