我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.INSTALLED_APPS。
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')
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 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 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 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
def setUp(self): settings.INSTALLED_APPS = [ 'zerodowntime', 'tests.safe_migrations', ] self.reinitialize_django_apps()
def add_django_app(self, app_module): settings.INSTALLED_APPS.append(app_module) self.reinitialize_django_apps()
def reinitialize_django_apps(self): apps.app_configs = OrderedDict() # set ready to false so that populate will work apps.ready = False # re-initialize them all; is there a way to add just one without reloading them all? apps.populate(settings.INSTALLED_APPS)
def test_registry(self): """Verify registration and autodiscovery work correctly. Please note that this implicitly tests that autodiscovery works by virtue of the fact that the dashboards listed in ``settings.INSTALLED_APPS`` are loaded from the start. """ # Registration self.assertEqual(2, len(base.Horizon._registry)) horizon.register(MyDash) self.assertEqual(3, len(base.Horizon._registry)) with self.assertRaises(ValueError): horizon.register(MyPanel) with self.assertRaises(ValueError): horizon.register("MyPanel") # Retrieval my_dash_instance_by_name = horizon.get_dashboard("mydash") self.assertIsInstance(my_dash_instance_by_name, MyDash) my_dash_instance_by_class = horizon.get_dashboard(MyDash) self.assertEqual(my_dash_instance_by_name, my_dash_instance_by_class) with self.assertRaises(base.NotRegistered): horizon.get_dashboard("fake") self.assertQuerysetEqual(horizon.get_dashboards(), ['<Dashboard: cats>', '<Dashboard: dogs>', '<Dashboard: mydash>']) # Removal self.assertEqual(3, len(base.Horizon._registry)) horizon.unregister(MyDash) self.assertEqual(2, len(base.Horizon._registry)) with self.assertRaises(base.NotRegistered): horizon.get_dashboard(MyDash)
def clean(self): if not (self.cleaned_data.get('thumbnail_option') or ((self.cleaned_data.get('width') or 0) + (self.cleaned_data.get('height') or 0))): if 'cmsplugin_filer_image' in settings.INSTALLED_APPS: raise ValidationError(_('Thumbnail option or resize parameters must be choosen.')) else: raise ValidationError(_('Resize parameters must be choosen.')) return self.cleaned_data
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: if os.environ.get('DJANGO_SETTINGS_MODULE'): # If `subcommand` is missing due to misconfigured settings, the # following line will retrigger an ImproperlyConfigured exception # (get_commands() swallows the original one) so the user is # informed about it. settings.INSTALLED_APPS else: sys.stderr.write("No Django settings specified.\n") 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 model_unpickle(model_id, attrs, factory): """ Used to unpickle Model subclasses with deferred fields. """ if isinstance(model_id, tuple): if not apps.ready: apps.populate(settings.INSTALLED_APPS) model = apps.get_model(*model_id) else: # Backwards compat - the model was cached directly in earlier versions. model = model_id cls = factory(model, attrs) return cls.__new__(cls)
def _pre_setup(self): """Performs any pre-test setup. This includes: * If the class has an 'available_apps' attribute, restricting the app registry to these applications, then firing post_migrate -- it must run with the correct set of applications for the test case. * If the class has a 'fixtures' attribute, installing these fixtures. """ super(TransactionTestCase, self)._pre_setup() if self.available_apps is not None: apps.set_available_apps(self.available_apps) setting_changed.send(sender=settings._wrapped.__class__, setting='INSTALLED_APPS', value=self.available_apps, enter=True) for db_name in self._databases_names(include_mirrors=False): emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name) try: self._fixture_setup() except Exception: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send(sender=settings._wrapped.__class__, setting='INSTALLED_APPS', value=settings.INSTALLED_APPS, enter=False) raise
def _post_teardown(self): """Performs any post-test things. This includes: * Flushing the contents of the database, to leave a clean slate. If the class has an 'available_apps' attribute, post_migrate isn't fired. * Force-closing the connection, so the next test gets a clean cursor. """ try: self._fixture_teardown() super(TransactionTestCase, self)._post_teardown() if self._should_reload_connections(): # Some DB cursors include SQL statements as part of cursor # creation. If you have a test that does a rollback, the effect # of these statements is lost, which can affect the operation of # tests (e.g., losing a timezone setting causing objects to be # created with the wrong time). To make sure this doesn't # happen, get a clean connection at the start of every test. for conn in connections.all(): conn.close() finally: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send(sender=settings._wrapped.__class__, setting='INSTALLED_APPS', value=settings.INSTALLED_APPS, enter=False)
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: if os.environ.get('DJANGO_SETTINGS_MODULE'): # If `subcommand` is missing due to misconfigured settings, the # following line will retrigger an ImproperlyConfigured exception # (get_commands() swallows the original one) so the user is # informed about it. settings.INSTALLED_APPS else: sys.stderr.write("No Django settings specified.\n") 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_verify_installed_apps(self): from django.conf import settings self.assertIn('modeltrans', settings.INSTALLED_APPS) self.assertNotIn('modeltranslation', settings.INSTALLED_APPS)
def test_verify_installed_apps(self): from django.conf import settings self.assertNotIn('modeltrans', settings.INSTALLED_APPS) self.assertIn('modeltranslation', settings.INSTALLED_APPS)
def _get_social_auth_providers(request): if 'allauth.socialaccount' not in settings.INSTALLED_APPS: return [] from allauth.socialaccount import providers return [{'name': provider.name, 'url': provider.get_login_url(request)} for provider in providers.registry.get_list()]
def get_current_site(self): if self.request: site = get_current_site(self.request) elif ('django.contrib.sites' in settings.INSTALLED_APPS and settings.SITE_ID): from django.contrib.sites.models import Site site = Site.objects.get_current() else: site = None return site
def load(self): from django.conf import settings for app in settings.INSTALLED_APPS: try: m = app + '.activities' import_module(m) except ImportError: pass
def is_installed(appname): return appname in settings.INSTALLED_APPS #or apps.is_installed(appname)
def __init__(self): super(NotificationMethod, self).__init__() if settings.EMAIL_BACKEND: self.server_configured = True if 'djembe' in settings.INSTALLED_APPS: self.options['certificate'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'cols': 60, 'rows': 15}), help_text=_('Encryption certificate in PEM format.'))
def ready(self): # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) if hasattr(settings, 'RAVEN_CONFIG'): # Celery signal registration from raven import Client as RavenClient from raven.contrib.celery import register_signal as raven_register_signal from raven.contrib.celery import register_logger_signal as raven_register_logger_signal raven_client = RavenClient(dsn=settings.RAVEN_CONFIG['DSN']) raven_register_logger_signal(raven_client) raven_register_signal(raven_client)
def load(): # Dynamically grab package name package_name = os.path.dirname(__file__) # For each registered app, import all of the available roles for app in settings.INSTALLED_APPS: # Make sure the app is not self if app is not package_name: try: import_module('.roles', app) except ImportError: pass # Registers a Role with the global Bootstrapper if it is not already registered. # Returns the True if Role is added, None if it already exists