在Django框架下實作的view的一個介面有以下幾行代碼:
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.submit(fn)
fn函式參考了Django的model物件
當新的行程加載model的時候報錯:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
新的行程沒有了原行程Apps的資訊
運行Django底層會觸發 django.setup()
以下是原碼:
def setup(set_prefix=True):
"""
Configure the settings (this happens as a side effect of accessing the
first setting), configure logging and populate the app registry.
Set the thread-local urlresolvers script prefix if `set_prefix` is True.
"""
from django.apps import apps
from django.conf import settings
from django.urls import set_script_prefix
from django.utils.log import configure_logging
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
if set_prefix:
set_script_prefix(
'/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
)
# 這里是apps注冊的方法,但目前得出的結論是只對當前行程有效
apps.populate(settings.INSTALLED_APPS)
請問怎么樣才能在多行程里共享Django的apps資訊
uj5u.com熱心網友回復:
試試 with concurrent.futures.ThreadPoolExecutor() as executor:executor.submit(fn)
或者,
executor.map(fn)
記憶中,submit 是非阻塞式的。
uj5u.com熱心網友回復:
因為ThreadPoolExecutor還是在原來的行程,所以并發可以正常執行
但ProcessPoolExecutor并行會創建新的行程,不同行程之間apps的資訊被隔離了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/267779.html
