Python: NameError: name request is not defined in Web Applications
This error occurs when Python tries to access the variable 'request' without importing it from your web framework or passing it as a function parameter. Add from flask import request or include request in your view parameters.
Root Cause Analysis
This error occurs when Python evaluates code referencing the identifier request inside a function, script, or class body, but the name request has not been bound in local, enclosing, global, or built-in namespaces.
Root Cause 1: Missing Framework Import Statement in Flask
In Flask, request is a global context proxy object exported by the flask package. If a developer uses request.args, request.form, or request.json inside a view function but omitted from flask import request at the top of the module, Python raises NameError: name 'request' is not defined.
Root Cause 2: Confusing Flask Global Proxy with Django Explicit Parameter
In Django, request is NOT a global object; it is explicitly passed as the first positional argument to every view function (def my_view(request): ...). If a developer forgets the request parameter in the function signature (e.g. def my_view(): return render(request, ...)), accessing request triggers a NameError.
Root Cause 3: Variable Shadowing and Scoping in Helper Functions
Calling a utility function from inside a view without passing the request object as an argument leaves the utility function with no access to the view's local request variable.
Root Cause 4: Typo in Variable Names
Accidentally writing requests (plural, the HTTP client library) instead of request (singular, the incoming web request proxy) or vice versa causes name resolution errors.
Reproduction Code (MCVE)
def process_incoming_request():
# Attempting to access request without import or parameter definition triggers NameError
return request.method
# Executing function triggers NameError: name 'request' is not defined
process_incoming_request()
Solution 1: Import request from Flask at Top of Module
Add the explicit import from flask import Flask, request at the top of your Flask application file.
from flask import Flask, request
app = Flask(__name__)
# Solution 1: Explicitly import request proxy from flask
@app.route("/api/echo", methods=["GET", "POST"])
def echo_handler():
# request is now properly imported and accessible in request context
return {
"method": request.method,
"endpoint": request.path
}
# Standalone test verifying imported symbol existence
print("Flask request symbol loaded successfully:", request.__class__.__name__)
assert request is not None
Solution 2: Pass request Object Explicitly to Helper Functions (Django / Clean Architecture)
In Django or modular architectures, pass the request object explicitly as a function parameter to keep functions testable and pure.
# Solution 2: Explicit parameter passing pattern (Django / Clean code)
class HttpRequestMock:
def __init__(self, method: str, user_ip: str):
self.method = method
self.user_ip = user_ip
def extract_client_metadata(req: HttpRequestMock) -> dict:
"""Pure helper function that receives request explicitly."""
return {
"http_method": req.method,
"ip_address": req.user_ip
}
mock_req = HttpRequestMock("GET", "192.168.1.50")
metadata = extract_client_metadata(mock_req)
print("Extracted metadata:", metadata)
assert metadata["http_method"] == "GET"
A common trap occurs in multi-threaded background workers (such as Celery tasks or background threads). Attempting to access Flask's request object inside a background thread will raise a RuntimeError: Working outside of request context because request proxies are thread-local and bound to incoming WSGI requests. Always extract the required data (like user_id = request.json['user_id']) in the view function and pass the raw data to the background task.
Another edge case is confusing requests (the outbound HTTP client library) with request (the inbound Flask request proxy).
Contrast NameError with AttributeError: NameError: name 'request' is not defined occurs when the identifier is completely unknown; AttributeError: 'Request' object has no attribute 'xxx' occurs when the request object exists but you accessed a non-existent property.