为什么在 Werkzeug 中绑定到上下文是必要的

Why binding to context is necessary in Werkzeug

我正在阅读 Werkzeug library in github and in one of the examples (Simplewiki 的源代码来命名),在 application.py 文件中有一个将应用程序绑定到当前活动上下文的函数。我想知道为什么这是必要的,或者我在哪里可以找到解释这个的东西?

函数是这样的:

def bind_to_context(self):
        """
        Useful for the shell.  Binds the application to the current active
        context.  It's automatically called by the shell command.
        """
        local.application = self

这是调度程序绑定请求的部分。

def dispatch_request(self, environ, start_response):
        """Dispatch an incoming request."""
        # set up all the stuff we want to have for this request.  That is
        # creating a request object, propagating the application to the
        # current context and instanciating the database session.
        self.bind_to_context()
        request = Request(environ)
        request.bind_to_context()

据我所知,Werkzeug中的contexts是关于在不同线程之间分离环境。例如,上下文在 Flask 框架中非常常见,它建立在 Werkzeug 之上。您可以在 multi-threaded 模式下 运行 Flask 应用程序。在这种情况下,您将只有一个被多个线程同时访问的应用程序对象。每个线程都需要应用程序中的一段数据供私人使用。存储此类数据是通过 thread's local storage 组织的。这就是所谓的上下文。