Flask Web Development says:
from flask import request
@app.route('/')
def index():
user_agent = request.headers.get('User-Agent')
return '<p>Your browser is %s</p>' % user_agent
Note how in this view function
request
is used as if it was a global variable. In reality,request
cannot be a global variable if you consider that in a multithreaded server the threads are working on different requests from different clients at the same time, so each thread needs to see a different object in request. Contexts enable Flask to make certain variables globally accessible to a thread without interfering with the other threads.
Understandable, but why not simply make request
a thread-local variable? Under the hood, what exactly is request
, and how is it different from a thread-local variable?