def ready(self):
# Monkey-patch `RedirectNodeAdmin` to replace `fieldsets` attribute
# with `base_fieldsets` to avoid infinitie recursion bug when using
# django-polymorphic versions >= 0.8 and < 1.1, see:
# https://github.com/django-fluent/django-fluent-pages/issues/110
from django.conf import settings
if 'fluent_pages.pagetypes.redirectnode' in settings.INSTALLED_APPS:
from fluent_pages.pagetypes.redirectnode.admin \
import RedirectNodeAdmin
if getattr(RedirectNodeAdmin, 'fieldsets', None):
RedirectNodeAdmin.base_fieldsets = RedirectNodeAdmin.fieldsets
RedirectNodeAdmin.fieldsets = None
# Connect signal handlers.
post_migrate.connect(update_site, sender=self)
# Import plugins from installed apps.
autodiscover_modules('plugins')
python类INSTALLED_APPS的实例源码
def get_context_data(self, **kwargs):
kwargs = super(ReportView, self).get_context_data(**kwargs)
kwargs['media'] = self.media
form = self.get_form(self.get_form_class())
if form is not None:
kwargs['form'] = form
if form.is_valid():
self.report.set_params(**form.cleaned_data)
rl = ReportList(self.request, self.report)
kwargs.update({
'rl': rl,
'title': self.report.get_title(),
'has_filters': self.get_form_class() is not None,
'help_text': self.report.get_help_text(),
'description': self.report.get_description(),
'export_path': rl.get_query_string({EXPORT_VAR: ''}),
'totals': self.report.get_has_totals(),
'totals_on_top': self.report.totals_on_top,
'suit': ('suit' in settings.INSTALLED_APPS) or ('bootstrap_admin' in settings.INSTALLED_APPS),
})
return kwargs
def get(self, request, *args, **kwargs):
"""
Django view get function.
Add items of extra_context, crumbs and grid to context.
Args:
request (): Django's request object.
*args (): request args.
**kwargs (): request kwargs.
Returns:
response: render to response with context.
"""
context = self.get_context_data(**kwargs)
context.update(self.extra_context)
context['crumbs'] = self.get_crumbs()
context['title'] = self.title
context['suit'] = 'suit' in settings.INSTALLED_APPS
if context.get('dashboard_grid', None) is None and self.grid:
context['dashboard_grid'] = self.grid
return self.render_to_response(context)
def _autodiscover(self):
"""Discovers modules to register from ``settings.INSTALLED_APPS``.
This makes sure that the appropriate modules get imported to register
themselves with Horizon.
"""
if not getattr(self, '_registerable_class', None):
raise ImproperlyConfigured('You must set a '
'"_registerable_class" property '
'in order to use autodiscovery.')
# Discover both dashboards and panels, in that order
for mod_name in ('dashboard', 'panel'):
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
before_import_registry = copy.copy(self._registry)
import_module('%s.%s' % (app, mod_name))
except Exception:
self._registry = before_import_registry
if module_has_submodule(mod, mod_name):
raise
def check_mandatory_apps_are_in_installed_apps(app_configs, **kwargs):
from django.conf import settings
errors = []
needed_modules = [
'corsheaders',
'elokenz_twote',
'rest_framework',
]
for module in needed_modules:
if module not in settings.INSTALLED_APPS:
errors.append(
Error(
'INSTALLED_APPS is incomplete',
hint="Add '{mod}' in your INSTALLED_APPS".format(
mod=module),
obj='Import Error',
id='contact_form.check',
)
)
return errors
def get_app_template_dir(app_name):
"""Get the template directory for an application
We do not use django.db.models.get_app, because this will fail if an
app does not have any models.
Returns a full path, or None if the app was not found.
"""
from django.conf import settings
from importlib import import_module
if app_name in _cache:
return _cache[app_name]
template_dir = None
for app in settings.INSTALLED_APPS:
if app.split('.')[-1] == app_name:
# Do not hide import errors; these should never happen at this point
# anyway
mod = import_module(app)
template_dir = join(abspath(dirname(mod.__file__)), 'templates')
break
_cache[app_name] = template_dir
return template_dir
def test_autopatching_twice_middleware(self):
ok_(django._datadog_patch)
# Call django.setup() twice and ensure we don't add a duplicate tracer
django.setup()
found_app = settings.INSTALLED_APPS.count('ddtrace.contrib.django')
eq_(found_app, 1)
eq_(settings.MIDDLEWARE[0], 'ddtrace.contrib.django.TraceMiddleware')
ok_('ddtrace.contrib.django.TraceMiddleware' not in settings.MIDDLEWARE_CLASSES)
eq_(settings.MIDDLEWARE[-1], 'ddtrace.contrib.django.TraceExceptionMiddleware')
ok_('ddtrace.contrib.django.TraceExceptionMiddleware' not in settings.MIDDLEWARE_CLASSES)
found_mw = settings.MIDDLEWARE.count('ddtrace.contrib.django.TraceMiddleware')
eq_(found_mw, 1)
found_mw = settings.MIDDLEWARE.count('ddtrace.contrib.django.TraceExceptionMiddleware')
eq_(found_mw, 1)
def load(modname):
""" Loads all the modules that are named 'modname' from all the installed applications. """
def _get_module(app, modname):
# Find out the app's __path__
try:
app_path = import_module(app).__path__
except AttributeError: # pragma: no cover
return
# Use imp.find_module to find the app's modname.py
try:
imp.find_module(modname, app_path)
except ImportError: # pragma: no cover
return
# Import the app's module file
import_module('{}.{}'.format(app, modname))
for app in settings.INSTALLED_APPS:
_get_module(app, modname)
def capabilities(request):
"""
The capabilities view is like the about page, but for consumption by code instead of humans.
It serves to provide information about the Exchange instance.
"""
capabilities = {}
capabilities["versions"] = {
'exchange': get_exchange_version(),
'geonode': get_pip_version('GeoNode'),
'geoserver': get_geoserver_version(),
}
mobile_extension_installed = "geonode_anywhere" in settings.INSTALLED_APPS
capabilities["mobile"] = (
mobile_extension_installed and
# check that the OAuth application has been created
len(Application.objects.filter(name='Anywhere')) > 0
)
current_site = get_current_site(request)
capabilities["site_name"] = current_site.name
return JsonResponse({'capabilities': capabilities})
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
# This might trigger ImproperlyConfigured (masked in get_commands)
settings.INSTALLED_APPS
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
(subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def lang_data(LANGUAGE_CODE, **kwargs):
# These are needed for i18n
from django.http import HttpRequest
from django.views.i18n import javascript_catalog
LANGUAGE_BIDI = LANGUAGE_CODE.split('-')[0] in \
settings.LANGUAGES_BIDI
request = HttpRequest()
request.GET['language'] = LANGUAGE_CODE
# Add some JavaScript data
content = 'var LANGUAGE_CODE = "%s";\n' % LANGUAGE_CODE
content += 'var LANGUAGE_BIDI = ' + \
(LANGUAGE_BIDI and 'true' or 'false') + ';\n'
content += javascript_catalog(request,
packages=settings.INSTALLED_APPS).content
# The hgettext() function just calls gettext() internally, but
# it won't get indexed by makemessages.
content += '\nwindow.hgettext = function(text) { return gettext(text); };\n'
# Add a similar hngettext() function
content += 'window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };\n'
return content
def get_file_path(handler, target, media_dirs, **kwargs):
if isinstance(handler, basestring):
path = handler % dict(kwargs, target=target)
app, filepath = path.replace('/', os.sep).split(os.sep, 1)
return os.path.abspath(os.path.join(media_dirs[app], filepath))
ext = os.path.splitext(target)[1]
owner = ''
for app in settings.INSTALLED_APPS:
if handler.__module__.startswith(app + '.') and len(app) > len(owner):
owner = app
owner = owner or handler.__module__
name = getattr(handler, 'name', handler.__name__ + ext) % dict(kwargs,
target=target)
assert '/' not in name
return os.path.join(DYNAMIC_MEDIA, '%s-%s' % (owner, name))
def updatemessages():
from django.conf import settings
if not settings.USE_I18N:
return
from django.core.management.commands.compilemessages import compile_messages
if any([needs_update(path) for path in settings.LOCALE_PATHS]):
compile_messages()
LOCALE_PATHS = settings.LOCALE_PATHS
settings.LOCALE_PATHS = ()
cwd = os.getcwdu()
for app in settings.INSTALLED_APPS:
path = os.path.dirname(__import__(app, {}, {}, ['']).__file__)
locale = os.path.join(path, 'locale')
if os.path.isdir(locale):
# Copy Python translations into JavaScript translations
update_js_translations(locale)
if needs_update(locale):
os.chdir(path)
compile_messages()
settings.LOCALE_PATHS = LOCALE_PATHS
os.chdir(cwd)
def render(self, context):
allowed = False
for app in self.apps:
if app.startswith('"') and app.endswith('"'):
app = app[1:-1]
if app.startswith("'") and app.endswith("'"):
app = app[1:-1]
if app in settings.INSTALLED_APPS:
allowed = True
else:
break
if allowed:
return self.nodelist_true.render(context)
else:
return self.nodelist_false.render(context)
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
# This might trigger ImproperlyConfigured (masked in get_commands)
settings.INSTALLED_APPS
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
(subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def add_message(self, request, level, message_template,
message_context=None, extra_tags=''):
"""
Wrapper of `django.contrib.messages.add_message`, that reads
the message text from a template.
"""
if 'django.contrib.messages' in settings.INSTALLED_APPS:
try:
if message_context is None:
message_context = {}
message = render_to_string(message_template,
message_context).strip()
if message:
messages.add_message(request, level, message,
extra_tags=extra_tags)
except TemplateDoesNotExist:
pass
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
# This might trigger ImproperlyConfigured (masked in get_commands)
settings.INSTALLED_APPS
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
(subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def test_create_with_revision_fail(self):
# tests that we're unable to create a page or title
# through the api with the revision option if reversion
# is not installed.
page_attrs = self._get_default_create_page_arguments()
page_attrs['language'] = 'en'
page_attrs['with_revision'] = True
apps = list(settings.INSTALLED_APPS)
apps.remove('reversion')
with self.settings(INSTALLED_APPS=apps):
with self.assertRaises(ImproperlyConfigured):
create_page(**page_attrs)
page = create_page(**page_attrs)
with self.settings(INSTALLED_APPS=apps):
with self.assertRaises(ImproperlyConfigured):
create_title('de', 'test de', page, with_revision=True)
def _find_installed_apps_entry(module_label):
"""
Given a module label, finds the best matching INSTALLED_APPS entry.
This is made trickier by the fact that we don't know what part of the
module_label is part of the INSTALLED_APPS entry. So we try all possible
combinations, trying the longer versions first. E.g. for
'dashboard.catalogue.forms', 'dashboard.catalogue' is attempted before
'dashboard'
"""
modules = module_label.split('.')
# if module_label is 'dashboard.catalogue.forms.widgets', combinations
# will be ['dashboard.catalogue.forms', 'dashboard.catalogue', 'dashboard']
combinations = [
'.'.join(modules[:-count]) for count in range(1, len(modules))]
for app_name in combinations:
entry = _get_installed_apps_entry(app_name)
if entry:
return entry, app_name
raise AppNotFoundError(
"Couldn't find an app to import %s from" % module_label)
def get_class(component_name):
class_name = snake_to_camel(component_name)
_class = None
try:
_class = registry[class_name]
except KeyError:
try:
possible_paths = [
os.path.join(app, 'components', component_name)
for app in settings.INSTALLED_APPS
if not app.startswith('django.')
]
module_info = imp.find_module(component_name, possible_paths)
module = imp.load_module(component_name, *module_info)
print module
_class = getattr(module, class_name)
except (AttributeError, ImportError):
_class = partial(MissingComponent, component_name=component_name)
return _class
def __init__(self):
for app in settings.INSTALLED_APPS:
api = importlib.util.find_spec(app + '.api')
if api is None:
logger.debug('No api calls found for module {}'.format(app))
else:
try:
importlib.import_module(app + '.api')
except ImportError as e:
logger.error(
'Loading api calls for module {} failed: {}'
.format(app, e)
)
raise
else:
logger.debug(
'Successfuly loaded api calls for module {}'
.format(app)
)
def __init__(self):
for app in settings.INSTALLED_APPS:
hook = importlib.util.find_spec(app + '.hooks')
if hook is None:
logger.debug('No hooks found for module {}'.format(app))
else:
try:
importlib.import_module(app + '.hooks')
except ImportError as e:
logger.error(
'Loading hooks for module {} failed: {}'.format(app, e)
)
raise
else:
logger.debug(
'Successfuly loaded hooks for module {}'.format(app)
)
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yawn.settings.debug")
# check if yawn is in installed apps, and bail if it is not
if 'yawn' not in settings.INSTALLED_APPS:
print("Please check your DJANGO_SETTINGS_MODULE environment variable.\n"
"Make sure 'yawn' is in your INSTALLED_APPS.\n"
"Generally, your settings file should start with 'from yawn.settings.base import *'")
sys.exit(1)
print('YAWN workflow management tool')
if os.environ['DJANGO_SETTINGS_MODULE'] == 'yawn.settings.debug':
print(' Running in DEBUG mode')
# run the django manage.py command line
execute_from_command_line(sys.argv)
def get_comment_app():
"""
Get the comment app (i.e. "django.contrib.comments") as defined in the settings
"""
# Make sure the app's in INSTALLED_APPS
comments_app = get_comment_app_name()
if comments_app not in settings.INSTALLED_APPS:
raise ImproperlyConfigured("The COMMENTS_APP (%r) "\
"must be in INSTALLED_APPS" % settings.COMMENTS_APP)
# Try to import the package
try:
package = import_module(comments_app)
except ImportError as e:
raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\
"a non-existing package. (%s)" % e)
return package
def load_modules(modules=None):
try:
import django # noqa
except ImportError:
# Not a django project
return
try: # pragma: no cover
from django.utils.module_loading import autodiscover_modules
except ImportError: # pragma: no cover
# Django 1.6 compat to provide `autodiscover_modules`
def autodiscover_modules(module_name):
from django.conf import settings
from django.utils.importlib import import_module
for app in settings.INSTALLED_APPS:
# Attempt to import the app's `module_name`.
try:
import_module('{app}.{module}'.format(app=app, module=module_name))
except Exception:
pass
for module in modules:
autodiscover_modules(module)
def check_installed_before_admin(app_configs=None, **kwargs):
"""
If `django.contrib.admin` is also installed, we must be installed before it.
Is this even true anymore?
"""
from django.conf import settings
errors = []
if 'django.contrib.admin' in settings.INSTALLED_APPS:
admin = settings.INSTALLED_APPS.index('django.contrib.admin')
local = settings.INSTALLED_APPS.index('boardinghouse')
if admin < local:
errors.append(Error(
"boardinghouse must be installed prior to 'django.contrib.admin'",
id='boardinghouse.E004',
))
return errors
def setUp(self):
self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
settings.TEMPLATE_DIRS = (
os.path.join(os.path.dirname(admin.__file__), "templates"),
)
self.user = User(
username = "foo",
is_staff = True,
is_superuser = True,
)
self.user.set_password("bar")
self.user.save()
# Log the user in.
if hasattr(self, "settings"):
with self.settings(INSTALLED_APPS=tuple(set(tuple(settings.INSTALLED_APPS) + ("django.contrib.sessions",)))): # HACK: Without this the client won't log in, for some reason.
self.client.login(
username = "foo",
password = "bar",
)
else:
self.client.login(
username = "foo",
password = "bar",
)
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
# This might trigger ImproperlyConfigured (masked in get_commands)
settings.INSTALLED_APPS
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
(subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def get_apps(self):
"""
Get the list of installed apps
and return the apps that have
an emails module
"""
templates = []
for app in settings.INSTALLED_APPS:
try:
app = import_module(app + '.emails')
templates += self.get_plugs_mail_classes(app)
except ImportError:
pass
return templates
def autodiscover():
"""
Auto-discover INSTALLED_APPS modules:
* page_processors.py to fill out the default PageProcessorRegistry,
* sitemap.py to populate sitemap_config.sitemaps.
Inspired by django.contrib.admin.autodiscover.
"""
from django.conf import settings
from django.utils.module_loading import module_has_submodule
from powerpages import page_processor_registry
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# page processors:
try:
before_import_registry = copy.copy(
page_processor_registry.registry.registry
)
import_module('%s.page_processors' % app)
except:
page_processor_registry.registry.registry = before_import_registry
if module_has_submodule(mod, 'page_processors'):
raise
# sitemaps:
try:
import_module('%s.sitemap' % app)
except:
if module_has_submodule(mod, 'sitemap'):
raise