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

3
我正在阅读Github上Werkzeug库的源代码,其中在一个示例(以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()
1个回答

1
据我所知,Werkzeug中的contexts是关于在不同线程之间分离环境的。例如,在基于Werkzeug构建的Flask框架中,上下文是非常常见的事情。您可以以多线程模式运行Flask应用程序。在这种情况下,您将只有一个应用程序对象,由多个线程同时访问。每个线程都需要应用程序内的一些数据进行私有使用。通过线程本地存储来组织存储这些数据。这就是所谓的上下文。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接