1

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?

Community
  • 1
  • 1
max
  • 49,282
  • 56
  • 208
  • 355

1 Answers1

1

This was simply a design decision by Armin (the author of Flask). You could indeed rewrite Flask to operate as a thread-local, but that was not what he wanted to do here.

The idea of Flask (in general) is to keep things as simple as possible, and abstract a lot of thinking away. This is why a lot of Flask helpers are implemented as 'global variables': you don't really have to think about the meaning behind it, because each global is bound to the incoming request.

rdegges
  • 32,786
  • 20
  • 85
  • 109
  • I just realized I don't understand how `session` works if it's thread-local, so I asked it as a [separate question](http://stackoverflow.com/questions/38818350/does-flask-session-variable-maintain-state-across-threads) – max Aug 07 '16 at 20:44