我希望文档说这background_thread
不是受支持的 API。
无论如何,我发现了一些技巧来帮助解决一些线程不兼容问题。App Engine 用于os.environ
读取大量设置。应用程序中的“真实”线程将在那里设置一堆环境变量。您启动的后台线程将没有。我使用的一种技巧是复制一些环境变量。例如,我需要SERVER_SOFTWARE
在后台线程中复制设置变量,以使 App Engine 云存储库正常工作。我们使用类似的东西:
_global_server_software = None
_SERVER_SOFTWARE = 'SERVER_SOFTWARE'
def environ_wrapper(function, args):
if _global_server_software is not None:
os.environ[_SERVER_SOFTWARE] = _global_server_software
function(*args)
def start_thread_with_app_engine_environ(function, *args):
# HACK: Required for the cloudstorage API on Flexible environment threads to work
# App Engine relies on a lot of environment variables to work correctly. New threads get none
# of those variables. loudstorage uses SERVER_SOFTWARE to determine if it is a test instance
global _global_server_software
if _global_server_software is None and os.environ.get(_SERVER_SOFTWARE) is not None:
_global_server_software = os.environ[_SERVER_SOFTWARE]
t = threading.Thread(target=environ_wrapper, args=(
function, args))
t.start()