1

I'm coming from Java world and I'm quite confused with variable scopes in Python:

from flask import Flask, request

@app.route('/', methods=['POST'])
def handle():
    form = request.form

In HTTP servers I worked with I was used to convention that variables like request are either passed as method parameters or retrieved from ThreadLocal. Why Flask/Python uses global variables in this case? Is it thread-safe?

dzieciou
  • 4,049
  • 8
  • 41
  • 85

2 Answers2

2

Flask uses some trickery so that each thread sees a different request object. They call this a "context", and it works similarly to thread-local variables.

See the documentation:

The context is unique to each thread (or other worker type). request cannot be passed to another thread, the other thread will have a different context stack and will not know about the request the parent thread was pointing to.

This is a design decision made by Flask to make things simple to write. Other frameworks may use other means such as explicitly passing in a Request object to the function.

interjay
  • 107,303
  • 21
  • 270
  • 254
  • I'm not sure if Flask uses them (probably not yet), but see also [PEP 555 -- Context-local variables](https://www.python.org/dev/peps/pep-0555/) – L3viathan Oct 24 '19 at 16:57
  • 1
    @L3viathan PEP 567 is the one that was accepted. Flask uses the Werkzeug library's context-local objects rather than the new `contextvars`. – interjay Oct 24 '19 at 17:09
-1

The variable is first searched in the local scope, if not found then it starts searching in global scope..

request is not defined in handle method thats why it used the global one

  • The question is how what seems like a global variable can work in a framework that supports multi-threading. – interjay Oct 24 '19 at 17:01