Flask Request Context - csrgxtu/Cocoa GitHub Wiki

what is request context?

When Flask receives a request from a client, it needs to make a few objects available to the view functions that will handle it. A good example of this is the request object, which encapsulates the HTTP request sent by the client.

The obvious way in which Flask could give a view function access to the request object is by sending it as an argument, but that would require every single view function in the application to have an extra argument. …

To avoid cluttering view functions with lots of arguments that may or may not be neded, Flask uses contexts to temporarily make certain objects globally accessible.

i.e request context contains all the data needed in the view functions, like sessions, url and arguments, request method etc.

class _RequestContext(object):
    def __init__(self, app, environ):
        self.app = app
        self.url_adapter = app.url_map.bind_to_environ(environ)
        self.request = app.request_class(environ)
        self.session = app.open_session(self.request)
        self.g = _RequestGlobals()
        self.flashes = None

    def __enter__(self):
        _request_ctx_stack.push(self)

    def __exit__(self, exc_type, exc_value, tb):
        if tb is None or not self.app.debug:
            _request_ctx_stack.pop()

request = LocalProxy(lambda: _request_ctx_stack.top.request)
from flask import request

request.args.get('username')

so, when create a new request context, first, push it into stack, then set the variables. when request finished, will pop it.

how flask seperate request context in concurrency?

If your web application running in thread mode, then each request will have a thread, thus related data to this request will only be local to this thread, other thread will not see the data in current thread.