Added a context manager to hold the import lock.

This commit is contained in:
Aymeric Augustin 2013-12-18 10:34:20 +01:00
parent 7f2485b4d1
commit 73c9e65b75
2 changed files with 15 additions and 6 deletions

View File

@ -1,7 +1,6 @@
"Utilities for loading models and the modules that contain them." "Utilities for loading models and the modules that contain them."
from collections import OrderedDict from collections import OrderedDict
import imp
from importlib import import_module from importlib import import_module
import os import os
import sys import sys
@ -9,7 +8,7 @@ import warnings
from django.conf import settings from django.conf import settings
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.utils.module_loading import module_has_submodule from django.utils.module_loading import import_lock, module_has_submodule
from django.utils._os import upath from django.utils._os import upath
from django.utils import six from django.utils import six
@ -74,8 +73,7 @@ class AppCache(object):
# without holding the importer lock and another thread then tries to # without holding the importer lock and another thread then tries to
# import something which also launches the app loading. For details of # import something which also launches the app loading. For details of
# this situation see #18251. # this situation see #18251.
imp.acquire_lock() with import_lock():
try:
if self.loaded: if self.loaded:
return return
for app_name in settings.INSTALLED_APPS: for app_name in settings.INSTALLED_APPS:
@ -86,8 +84,6 @@ class AppCache(object):
for app_name in self.postponed: for app_name in self.postponed:
self.load_app(app_name) self.load_app(app_name)
self.loaded = True self.loaded = True
finally:
imp.release_lock()
def load_app(self, app_name, can_postpone=False): def load_app(self, app_name, can_postpone=False):
""" """

View File

@ -1,5 +1,6 @@
from __future__ import absolute_import # Avoid importing `importlib` from this package. from __future__ import absolute_import # Avoid importing `importlib` from this package.
from contextlib import contextmanager
import copy import copy
import imp import imp
from importlib import import_module from importlib import import_module
@ -35,6 +36,18 @@ def import_by_path(dotted_path, error_prefix=''):
return attr return attr
@contextmanager
def import_lock():
"""
Context manager that aquires the import lock.
"""
imp.acquire_lock()
try:
yield
finally:
imp.release_lock()
def autodiscover_modules(*args, **kwargs): def autodiscover_modules(*args, **kwargs):
""" """
Auto-discover INSTALLED_APPS modules and fail silently when Auto-discover INSTALLED_APPS modules and fail silently when