Flask Request Lifecycle
Understanding the complete lifecycle of a Flask request is the key to writing good Flask applications.
This chapter breaks down, at the source-code level, the entire process of an HTTP request from entering the server to returning a response, helping you build a clear execution model.
What Is the Request Lifecycle
The request lifecycle refers to the complete processing procedure an HTTP request undergoes inside Flask.
It includes the following stages: receive request → create context → preprocess → route dispatch → view execution → response building → clean up context → return response.
Understanding this process lets you correctly answer the following questions:
- When is the data in the g object available? When is it cleaned up?
- What is the execution order of before_request and after_request?
- Which processing stages does an exception pass through in order?
- Why does using request outside a view function cause an error?
Complete Flow Diagram
The following diagram shows the complete call chain of Flask from receiving a request to returning a response:
Step-by-Step Explanation
Phase 1: WSGI Entry Point
When an HTTP request arrives at the server, the WSGI server (such as Gunicorn or the Werkzeug development server) calls the Flask application instance.
Flask implements the call method, making it a valid WSGI application:
Example
Simplified Flask source code (actual location: flask/app.py)
The WSGI server calls your application like this:
response = app(environ, start_response)
class
Flask
(
App
)
:
def
call
(
self
,
environ
,
start_response
)
:
"""Entry point called by the WSGI server"""
return
self
.
wsgi_app
(
environ
,
start_response
)
def
wsgi_app
(
self
,
environ
,
start_response
)
:
"""The actual WSGI processing logic"""
Step 1: Create the request context from environ
ctx
=
self
.
request_context
(
environ
)
try
:
ctx.
push
(
)
Push onto the context stack
response
=
self
.
full_dispatch_request
(
ctx
)
Full dispatch
except
Exception
as
e:
response
=
self
.
handle_exception
(
ctx
,
e
)
Exception fallback
finally
:
ctx.
pop
(
error
)
Pop the context and perform cleanup
return
response
(
environ
,
start_response
)
Flask designs the entry point to call the wsgi_app method rather than writing logic directly in the __call__ . This way you can insert middleware by replacing the app.wsgi_app without affecting calls to the app instance itself.
Phase 2: Creating the Context
request_context(environ) creates an AppContext object from the WSGI environment variables.
This object contains all information about the current request. Once it is pushed onto the stack, the global proxies request, session, g, and current_app begin to point to the current request's data.
Example
A Simple Experiment to Understand Context
from
flask
import
Flask
,
request
,
current_app
app
=
Flask
(
name
)
with
app.
app_context
(
)
:
Only application context—current_app is available, request is not
(
current_app.
name
)
✓ OK
print(request.method) # ✗ Error: Working outside of request context
with
app.
test_request_context
(
"/hello?name=runoob"
)
:
The request context also includes the application context—both are available
(
current_app.
name
)
✓ Outputs the app name
(
request.
path
)
✓ Outputs /hello
(
request.
args
[
"name"
]
)
✓ Outputs runoob
| Context Type | When Created | When Destroyed | Available global variables |
|---|---|---|---|
| Application context | When a request arrives / manually with app.app_context() | When the request ends / when the with block exits | current_app, g |
| Request context | When a request arrives / manually with app.test_request_context() | When the request ends / when the with block exits | request, session (including all variables of the application context) |
The most common mistake beginners make is directly accessing at module level request. Remember:request exists only in the request context. You can only access it inside a view function (or in functions it calls).
Phase 3: preprocess_request (preprocessing)
Once the context is ready, full_dispatch_request first calls preprocess_request.
This phase executes all functions registered with @app.before_request.
If any before_request function returns a value other than None, Flask treats it as the final response and skips the subsequent view function execution.
Example
from
flask
import
Flask
,
request
,
session
,
redirect
,
url_for
app
=
Flask
(
name
)
app.
secret_key
=
"dev-secret"
@
app.
before_request
def
check_authentication
(
)
:
"""Check whether the user is logged in before each request"""
Skip the authentication check for the login and registration pages
if
request.
endpoint
in
(
"login"
,
"register"
,
"static"
)
:
return
None
None means continue with the normal flow
If not logged in, return a redirect response directly (skipping the view function)
if
"username"
not
in
session:
return
redirect
(
url_for
(
"login"
)
)
The user is logged in, continue normally
return
None
@
app.
route
(
"/login"
,
methods
=
[
"GET"
,
"POST"
]
)
def
login
(
)
:
if
request.
method
==
"POST"
:
session
[
"username"
]
=
request.
form
[
"username"
]
return
redirect
(
url_for
(
"dashboard"
)
)
return
'
'@
app.
route
(
"/register"
)
def
register
(
)
:
return
"Registration page (no login required)"
@
app.
route
(
"/dashboard"
)
def
dashboard
(
)
:
return
f
"Welcome {session['username']} to the RUNOOB console"
Phase 4: dispatch_request (route dispatching)
After preprocessing, Flask enters the core dispatching phase:
- Match the URL to the corresponding routing rule (Rule)
- Extract the variable arguments from the URL (view_args)
- Call the corresponding view function, passing in the extracted arguments
Example
Simplified source code: how dispatch_request works
def
dispatch_request
(
self
,
ctx
)
:
req
=
ctx.
request
Get the matched routing rule (Rule object)
rule
=
req.
url_rule
Get the variable arguments in the URL. For example /post/42 → {"post_id": 42}
view_args
=
req.
view_args
Find the corresponding function in the view_functions dictionary and call it
return
self
.
view_functions
[
rule.
endpoint
]
(
**view_args
)
When matching fails, a RoutingException is raised, which is eventually caught by the error handler and returns 404.
Phase 5: view function execution
This is where you write your business logic. Flask calls your view function and obtains its return value.
The return value can be of many types—string, dict, tuple, Response object—all of which are handled uniformly in the next phase.
Phase 6: finalize_request (response building)
After the view function finishes, finalize_request is responsible for converting the return value into a standard Response object:
Example
Simplified source code: how finalize_request works
def
finalize_request
(
self
,
ctx
,
rv
)
:
1. Call make_response to convert various types of return values into a Response object
response
=
self
.
make_response
(
rv
)
2. Execute the after_request hooks via process_response
response
=
self
.
process_response
(
ctx
,
response
)
3. Send the signal: request_finished
request_finished.
send
(
self
,
response
=
response
)
return
response
make_response conversion rules:
| Return value type | Conversion method |
|---|---|
| str / bytes | As the response body, Content-Type: text/html |
| dict / list | Call jsonify(), Content-Type: application/json |
| tuple | Parse as (body, status) or (body, headers) |
| Response Object | Use directly |
| iterator / generator | As a streaming response |
Phase 7: after_request hook
After executing make_response, process_response calls all functions registered with @app.after_request in turn.
Each after_request function receives and returns a Response object, and can modify response headers, add cookies, etc.
Example
Typical use of after_request: add security headers to every response
@
app.
after_request
def
add_security_headers
(
response
)
:
response.
headers
[
"X-Content-Type-Options"
]
=
"nosniff"
response.
headers
[
"X-Frame-Options"
]
=
"DENY"
response.
headers
[
"X-XSS-Protection"
]
=
"1; mode=block"
return
response
Must return the response object
Also commonly used to add CORS headers
@
app.
after_request
def
add_cors_headers
(
response
)
:
response.
headers
[
"Access-Control-Allow-Origin"
]
=
"*"
response.
headers
[
"Access-Control-Allow-Methods"
]
=
"GET, POST, PUT, DELETE"
return
response
Phase 8: context cleanup
After the response is sent, ctx.pop() in the finally block performs context cleanup:
- Call all functions registered with teardown_request (executed whether the request succeeds or fails)
- Call all functions registered with teardown_appcontext
- Send the request_tearing_down and appcontext_tearing_down signals
- Release all data stored in the g object
Example
Typical use of teardown: close the database connection
@
app.
teardown_appcontext
def
close_database_connection
(
error
)
:
"""Ensure the database connection is closed even if the request fails"""
db
=
g.
pop
(
"db"
,
None
)
if
db
is
not
None
:
db.
close
(
)
The error parameter: if an exception occurs during the request, it will be received here
if
error:
app.
logger
.
warning
(
f
"Request error, database connection closed: {error}"
)
The difference between teardown and after_request
@
app.
after_request
def
after
(
response
)
:
after_request executes in the normal flow, but not when an exception occurs
Used to modify successful responses
return
response
@
app.
teardown_request
def
teardown
(
error
)
:
teardown always executes—whether the request succeeds or fails
Used to clean up resources (close files, release locks, etc.)
pass
Exception handling flow
When a view function raises an exception, Flask has a dedicated exception handling path:
- full_dispatch_request catches the exception
- Call handle_user_exception to determine the exception type
- HTTP exceptions (such as abort(404)) → find the corresponding errorhandler
- Ordinary exceptions → find the errorhandler for the exception class
- No handler found → call handle_exception, returning a 500 error
- Whether or not there is an exception, the response is ultimately built via finalize_request
Key points in the exception path:after_request Hooks are also executed for error responses (since Flask 1.1), but before_request a returned non-None value short-circuits the entire flow, so subsequent view functions and hooks will not execute.
Hook function quick reference
| Hook | Registration method | Execution Timing | Typical use |
|---|---|---|---|
| before_request | @app.before_request | Before route dispatch | Login checks, request logging, permission verification |
| before_first_request | @app.before_request (deprecated) | Before the first request (only once) | Initialization operations (consider using the factory pattern instead) |
| after_request | @app.after_request | After the response is built, before it is sent | Add response headers, CORS, logging |
| teardown_request | @app.teardown_request | When the request context is popped (always executed) | Release resources, close files |
| teardown_appcontext | @app.teardown_appcontext | When the application context is popped (always executed) | Close the database connection, clear the cache |
| errorhandler | @app.errorhandler(code) | When the corresponding error code/exception occurs | Custom error pages |
Signal events
Flask uses the blinker library to send signals at key points:
Example
from
flask
import
Flask
,
signals
app
=
Flask
(
name
)
Connect a signal—log when a request arrives
@
signals.
request_started
.
connect_via
(
app
)
def
log_request_start
(
sender
,
**extra
)
:
(
"Request started"
)
Connect a signal—log when a request completes
@
signals.
request_finished
.
connect_via
(
app
)
def
log_request_end
(
sender
,
response
,
**extra
)
:
(
f
"Request finished, response status code: {response.status_code}"
)
Connect a signal—catch exceptions
@
signals.
got_request_exception
.
connect_via
(
app
)
def
log_exception
(
sender
,
exception
,
**extra
)
:
(
f
"Exception occurred during request: {exception}"
)
| Signal | Trigger Timing |
|---|---|
| request_started | After the request context is established, before preprocessing |
| request_finished | After the response is built, before it is sent |
| got_request_exception | When an exception occurs during request processing |
| request_tearing_down | When the request context is destroyed |
| appcontext_pushed | When the application context is pushed onto the stack |
| appcontext_popped | When the application context is popped from the stack |
| message_flashed | When flash() is called |
| template_rendered | When template rendering succeeds |
Summary of Key Points
Core rule: In a complete request lifecycle,before_request → View Functions → after_request → teardown these four nodes are always executed in order (teardown always executes, regardless of whether the first three fail).
After understanding the request lifecycle, when writing Flask applications you know: put the authentication logic in before_request, the business logic in the view function, and response header modifications in after_request, and resource cleanup in teardown。