Python 中的记忆在请求之间持续存在

Memoization in Python persisting between requests

我今天早些时候遇到了这种技术,但不确定它是如何工作的。我认为这对这个例子来说并不重要,但我正在为应用程序使用 Django。

def post_to_endpoint(request, key=None):
    if not hasattar(post_to_endpoint, '__my_memo__'):
        post_to_endpoint.__my_memo__ = {
            "key1": "url" + "path",
            "key2": "url2" + "path",
            "key3": "url3" + "path",
            "key4": "url4" + "path",
        }

    if key:
        url = post_to_endpoint.__my_memo__.get(key, None)

        if url:
            # make my request here

    # return the response    

我明白在这个人为的例子中它可能是一个微优化。在我的函数中,我会在每次调用时重新创建 dict 。在基本层面上,我知道这个 dict 隐藏在一个叫做 func_dict 的东西中,但我真正不明白的是它如何存在于请求之间。

我对 PHP 背景的理解是,整个框架在每次请求时都会初始化,但也许 Python/Django/WSGI 不是这种情况?我也不太了解 运行 和 processes/threads 的所有这些,也许这些信息在那里保持活跃?我原以为需要在某种持久缓存中完成这样的事情,但显然情况并非如此。

此外,其他地方的张贴者也提到通过 import 字典也可以实现记忆,但我也不明白这在请求之间如何存在。

丹尼尔罗斯曼在评论中回答了这个问题:

"You've answered the question yourself. A WSGI app runs in a separate process (or many processes), which persists for many requests"