gpt4 book ai didi

python - Google App Engine api 的命名空间管理器的范围是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 04:56:26 24 4
gpt4 key购买 nike

我正在通过多个域提供服务的 Google App Engine Python 标准环境中使用 Flask 构建 API。

API 可用于存储数据和获取数据。

我想使用云数据存储的 Multi-Tenancy 功能仅在由访问 API 的域确定的命名空间中存储或获取数据。

我能看到的唯一方法是使用 google.appengine.api.namespace_manager 在请求时或在 I/O 时在上下文管理器中设置命名空间。

我写了这个上下文管理器:

@contextmanager
def multitenancy_namespace(namespace):
original_namespace = namespace_manager.get_namespace()
if namespace:
new_namespace = to_namespace_safe_url(namespace)
namespace_manager.set_namespace(new_namespace)

yield

namespace_manager.set_namespace(original_namespace)

它按预期工作。

我担心的是 namespace_manager 的范围。我找不到任何关于此的文档。

如果我的 API 是线程化的并且被 >1000 个用户同时使用,假设 namespace_manager.set_namespace(...) 设置的命名空间是全局的,我预计会发生一些冲突 - 数据被存储在错误的命名空间中,因为另一个请求在第一个请求之后调用了 set_namespace,但在第一个请求执行其 I/O 之前。

我写了一个线程测试here那通过了,这告诉我 namespace 的范围至少限于单个线程(这对我的 Flask 应用程序来说已经足够好了)。

但是namespace_manager 的上下文是什么set_namespace 实际上做了什么?命名空间设置保存在哪里?是否存在 namespace 冲突可能发生的用例?

最佳答案

如果您查看 source codenamespace_manager.set_namespace(...) 中,您会看到它是通过将命名空间设置为环境变量来实现的:

def set_namespace(namespace):
"""Set the default namespace for the current HTTP request.
Args:
namespace: A string naming the new namespace to use. A value of None
will unset the default namespace value.
"""
if namespace is None:
os.environ.pop(_ENV_CURRENT_NAMESPACE, None)
else:
validate_namespace(namespace)
os.environ[_ENV_CURRENT_NAMESPACE] = namespace

当线程切换上下文时,AppEngine 会根据需要备份和恢复环境变量。它们保证受请求限制,因此它对用户代码是不透明的。我不记得是否有这方面的文档,我想我是在某个论坛帖子上学到的。

注释 Set the default namespace for the current HTTP request 隐含地证实了这一点。

我们在 www.myclasses.org 使用它几年了,这从来都不是问题。

放轻松,在多线程环境中使用它是安全的!

关于python - Google App Engine api 的命名空间管理器的范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46943545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com