我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.apps.apps.get_app_config()。
def handle(self, *args, **options): validate = options.get('validate', False) force = options.get('force', False) app_config = apps.get_app_config('postgresviews') tables = { model._meta.db_table: model for model in apps.get_models() } for model in ViewBase.view_models: app_config.validate_view_model(model, tables) if validate: return if force: drop_views() create_views()
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict(self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict( self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
def parse_apps_and_model_labels(labels): """ Parse a list of "app_label.ModelName" or "app_label" strings into actual objects and return a two-element tuple: (set of model classes, set of app_configs). Raise a CommandError if some specified models or apps don't exist. """ apps = set() models = set() for label in labels: if '.' in label: try: model = installed_apps.get_model(label) except LookupError: raise CommandError('Unknown model: %s' % label) models.add(model) else: try: app_config = installed_apps.get_app_config(label) except LookupError as e: raise CommandError(str(e)) apps.add(app_config) return models, apps
def django_sending_elasticapm_client(request, validating_httpserver): validating_httpserver.serve_content(code=202, content='', headers={'Location': 'http://example.com/foo'}) client_config = getattr(request, 'param', {}) client_config.setdefault('server_url', validating_httpserver.url) client_config.setdefault('service_name', 'app') client_config.setdefault('secret_token', 'secret') client_config.setdefault('transport_class', 'elasticapm.transport.http.Transport') app = apps.get_app_config('elasticapm.contrib.django') old_client = app.client client = DjangoClient(**client_config) register_handlers(client) instrument(client) app.client = client client.httpserver = validating_httpserver yield client app.client = old_client if old_client: register_handlers(old_client) instrument(old_client)
def __init__(self, channel_id): self.channel_id = channel_id self.source = Bridge(sqlite_file_path=get_content_database_file_path(channel_id)) self.destination = Bridge(app_name=CONTENT_APP_NAME) content_app = apps.get_app_config(CONTENT_APP_NAME) # Use this rather than get_models, as it returns a list of all models, including those # generated by ManyToMany fields, whereas get_models only returns explicitly defined # Model classes self.content_models = list(content_app.get_models(include_auto_created=True)) # Get the next available tree_id in our database self.tree_id = self.find_unique_tree_id()
def setUpClass(cls): """ The setUpClass is used because the templates paths are not changed in the following tests. """ super(TestBase, cls).setUpClass() # Find directories with templates templates_dir = settings.TEMPLATES[0]['DIRS'][0] app = apps.get_app_config('app') app_templates = os.path.join(app.path, 'templates', 'app', 'templates') app_tags = os.path.join(app.path, 'templates', 'app', 'tags') # Save the path of each template for further testing cls.master_template = os.path.join(templates_dir, 'master.html') cls.tag_template = os.path.join(app_tags, 'tag_template.html') cls.double_loads = os.path.join(app_templates, 'double_loads.html') cls.with_tags = os.path.join(app_templates, 'with_tags.html') cls.without_tags = os.path.join(app_templates, 'without_tags.html') cls.from_syntax_with_tags = os.path.join(app_templates, 'from_syntax_with_tags.html') cls.from_syntax_without_tags = os.path.join(app_templates, 'from_syntax_without_tags.html') cls.double_member_load = os.path.join(app_templates, 'double_member_load.html') cls.only_filter = os.path.join(app_templates, 'only_filter.html')
def setUp(self): class Meta: permissions = ( ("copy_apptestmodel3", "Can copy apptestmodel3"), ) attrs_1 = { '__module__': 'tests.test_app.models', } attrs_2 = { '__module__': 'tests.test_app.models', 'Meta': Meta, } self.appconfig = apps.get_app_config('test_app') self.model1 = type(str('AppTestModel1'), (models.Model, ), attrs_1.copy()) self.model2 = type(str('AppTestModel2'), (models.Model, ), attrs_1.copy()) self.model3 = type(str('AppTestModel3'), (models.Model, ), attrs_2.copy())
def get_index_mapping(index): """Return the JSON mapping file for an index. Mappings are stored as JSON files in the mappings subdirectory of this app. They must be saved as {{index}}.json. Args: index: string, the name of the index to look for. """ # app_path = apps.get_app_config('elasticsearch_django').path mappings_dir = get_setting('mappings_dir') filename = '%s.json' % index path = os.path.join(mappings_dir, filename) with open(path, 'r') as f: return json.load(f)
def test_redirects_app_config(): """Test 'redirects' module `AppConfig` instance""" redirects_app_config = fakester_apps.get_app_config('redirects') assert isinstance(redirects_app_config, AppConfig) assert redirects_app_config.name == 'redirects' assert redirects_app_config.verbose_name == 'redirects'
def handle(self, *app_labels, **options): from django.apps import apps try: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] except (LookupError, ImportError) as e: raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e) output = [] for app_config in app_configs: app_output = self.handle_app_config(app_config, **options) if app_output: output.append(app_output) return '\n'.join(output)
def handle(self, *app_labels, **options): include_deployment_checks = options['deploy'] if options.get('list_tags'): self.stdout.write('\n'.join(sorted(registry.tags_available(include_deployment_checks)))) return if app_labels: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] else: app_configs = None tags = options.get('tags') if tags: try: invalid_tag = next( tag for tag in tags if not checks.tag_exists(tag, include_deployment_checks) ) except StopIteration: # no invalid tags pass else: raise CommandError('There is no system check with the "%s" tag.' % invalid_tag) self.check( app_configs=app_configs, tags=tags, display_num_errors=True, include_deployment_checks=include_deployment_checks, )
def migrations_module(cls, app_label): if app_label in settings.MIGRATION_MODULES: return settings.MIGRATION_MODULES[app_label] else: app_package_name = apps.get_app_config(app_label).name return '%s.%s' % (app_package_name, MIGRATIONS_MODULE_NAME)
def handle(self, *app_labels, **options): include_deployment_checks = options['deploy'] if options['list_tags']: self.stdout.write('\n'.join(sorted(registry.tags_available(include_deployment_checks)))) return if app_labels: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] else: app_configs = None tags = options['tags'] if tags: try: invalid_tag = next( tag for tag in tags if not checks.tag_exists(tag, include_deployment_checks) ) except StopIteration: # no invalid tags pass else: raise CommandError('There is no system check with the "%s" tag.' % invalid_tag) self.check( app_configs=app_configs, tags=tags, display_num_errors=True, include_deployment_checks=include_deployment_checks, fail_level=getattr(checks, options['fail_level']), )
def set_options(self, **options): """ Set instance variables based on an options dict """ self.interactive = options['interactive'] self.verbosity = options['verbosity'] self.symlink = options['link'] self.clear = options['clear'] self.dry_run = options['dry_run'] ignore_patterns = options['ignore_patterns'] if options['use_default_ignore_patterns']: ignore_patterns += apps.get_app_config('staticfiles').ignore_patterns self.ignore_patterns = list(set(ignore_patterns)) self.post_process = options['post_process']
def get_next_migration_filename(app_name, connection=None, migration_type='data'): ''' Return name (including the absolute path) of the next migration to insert for this app ''' latest_migration_name = get_latest_migration(app_name) next_migration_name = '{0:04d}_i18n_{1}_migration.py'.format( int(latest_migration_name[0:4]) + 1, migration_type ) app_path = os.path.join(*apps.get_app_config(app_name).name.split('.')) return os.path.join(settings.BASE_DIR, app_path, 'migrations', next_migration_name)
def get_translated_models(app_name): ''' Return models having a i18n = TranslationField() for given app_name. ''' app = apps.get_app_config(app_name) for model in app.get_models(): i18n_field = get_i18n_field(model) if i18n_field is not None: yield model
def candidate_party(candidate_name, year, election_type, office): """ Returns the correct OCD party organization object for a given candidate name, year, election_type and office. Returns None if no correction is found. """ from calaccess_processed.models.proxies import OCDPartyProxy # Get the path to our corrections file app = apps.get_app_config("calaccess_processed") module_dir = os.path.abspath(os.path.dirname(app.module.__file__)) corrections_path = os.path.join(module_dir, 'corrections', "candidate_party.csv") # Open up the corrections with open(corrections_path, 'r') as f: corrections = csv.DictReader(f) # Filter down to the ones we've corrected corrections = [d for d in corrections if d['party']] # Filter down to the ones that match matches = [ d['party'] for d in corrections if ( d['candidate_name'] == candidate_name and str(d['year']) == str(year) and d['election_type'] == election_type and d['office'] == office ) ] # If there's more than one result throw an error if len(matches) > 1: raise Exception('More than one correction found.') # If there's no match return None elif len(matches) == 0: return None # If there's only one match return that else: return OCDPartyProxy.objects.get_by_name(matches[0])
def get_model_list(self): return apps.get_app_config('elections').models.values() + apps.get_app_config('core').models.values()
def test_sendable_email_works(): cfg = django_apps.get_app_config('emailpal') assert cfg.sendable_emails == [MySendableEmail]
def get_sendable_emails() -> OrderedDict: return apps.get_app_config('emailpal').get_sendable_emails()
def get_config_instance(app_name=None): """ :rtype: DjangoSuitConfig() """ try: config = apps.get_app_config(app_name or 'suit') if isinstance(config, DjangoSuitConfig): return config except LookupError: pass return apps.get_app_config('suit') #: :type: DjangoSuitConfig()