我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.apps()。
def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have resolved a string-based reference to a model in another model's foreign key definition. String representations should have the format: 'appname.ModelName' """ if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: app_name, model_name = obj.split('.') resolved_model = apps.get_model(app_name, model_name) if resolved_model is None: msg = "Django did not return a model for {0}.{1}" raise ImproperlyConfigured(msg.format(app_name, model_name)) return resolved_model elif inspect.isclass(obj) and issubclass(obj, models.Model): return obj raise ValueError("{0} is not a Django model".format(obj))
def mock_django_setup(settings_module, disabled_features=None): """ Must be called *AT IMPORT TIME* to pretend that Django is set up. This is useful for running tests without using the Django test runner. This must be called before any Django models are imported, or they will complain. Call this from a module in the calling project at import time, then be sure to import that module at the start of all mock test modules. Another option is to call it from the test package's init file, so it runs before all the test modules are imported. :param settings_module: the module name of the Django settings file, like 'myapp.settings' :param disabled_features: a list of strings that should be marked as *False* on the connection features list. All others will default to True. """ if apps.ready: # We're running in a real Django unit test, don't do anything. return if 'DJANGO_SETTINGS_MODULE' not in os.environ: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module django.setup() mock_django_connection(disabled_features)
def get_yaml_for_all_models(self, schema): models = django.apps.apps.get_models() ct = 0 self.stdout.write(" ") self.stdout.write("Create .yaml for these models in schema " + str(schema) + " :") self.stdout.write(" ") for model in models: self.stdout.write(model._meta.db_table) if schema != 'public': data = serializers.serialize("yaml", model.objects.all()) dir = BASE_DIR + "/crm/fixtures/yamlsrc/" + str(schema)+'__'+model._meta.model_name + ".yaml" ct += 1 with open(dir, "w") as out: print(data, end="", file=out) self.stdout.write(" ") self.stdout.write("Number of created .yaml for schema "+str(schema)+" are " + str(ct)) self.total_yaml_created+=ct
def check_migrations(): from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.executor import MigrationExecutor from django.db.migrations.state import ProjectState changed = set() print("Checking {} migrations...".format(APP_NAME)) for db in settings.DATABASES.keys(): try: executor = MigrationExecutor(connections[db]) except OperationalError as e: sys.exit( "Unable to check migrations due to database: {}".format(e) ) autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps), ) changed.update( autodetector.changes(graph=executor.loader.graph).keys() ) if changed and APP_NAME in changed: sys.exit( "A migration file is missing. Please run " "`python makemigrations.py` to generate it." ) else: print("All migration files present.")
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 get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core commands are always included. If a settings module has been specified, user-defined commands will also be included. The dictionary is in the format {command_name: app_name}. Key-value pairs from this dictionary can then be used in calls to load_command_class(app_name, command_name) If a specific version of a command must be loaded (e.g., with the startapp command), the instantiated module can be placed in the dictionary in place of the application name. The dictionary is cached on the first call and reused on subsequent calls. """ commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))} if not settings.configured: return commands for app_config in reversed(list(apps.get_app_configs())): path = os.path.join(app_config.path, 'management') commands.update({name: app_config.name for name in find_commands(path)}) return commands
def is_installed(appname): return appname in settings.INSTALLED_APPS #or apps.is_installed(appname)
def get_django_model(app_label, model_name): return apps.get_model(app_label, model_name)
def get_installed_apps(): installed_apps = [] for app_config in apps.get_app_configs(): try: installed_apps.append([app_config.name, get_distribution(app_config.name).version]) except: pass return installed_apps
def get_metadata_model(): try: if (1, 11) > django.VERSION: return apps.get_model(get_config()['METADATA_MODEL']) else: return apps.get_model(get_config()['METADATA_MODEL'], require_ready=False) except ValueError: raise ImproperlyConfigured("METADATA_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "METADATA_MODEL refers to model '%s' that has not been installed" % get_config()['METADATA_MODEL'] )
def setup(): DB_FILE = NAME + '.db' with open(DB_FILE, 'w'): pass # wipe the database settings.configure( DEBUG=True, DATABASES={ DEFAULT_DB_ALIAS: { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DB_FILE}}, LOGGING={'version': 1, 'disable_existing_loggers': False, 'formatters': { 'debug': { 'format': '%(asctime)s[%(levelname)s]' '%(name)s.%(funcName)s(): %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}}, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'debug'}}, 'root': { 'handlers': ['console'], 'level': 'WARN'}, 'loggers': { "django.db": {"level": "WARN"}}}) app_config = AppConfig(NAME, sys.modules['__main__']) apps.populate([app_config]) django.setup() original_new_func = ModelBase.__new__ @staticmethod def patched_new(cls, name, bases, attrs): if 'Meta' not in attrs: class Meta: app_label = NAME attrs['Meta'] = Meta return original_new_func(cls, name, bases, attrs) ModelBase.__new__ = patched_new
def setup(): """ Configure Django enough to use the ORM. """ cfg = config.parser(section='web_portal') # INSTALLED_APPS doesn't seem necessary so long as you are only accessing # existing tables. # # Setting charset to latin1 is a disgusting kludge, but without # this MySQL 5.6 (and, proably, later) gets tetchy about ASN.1 DER # stored in BLOB columns not being well-formed UTF8 (sic). If you # know of a better solution, tell us. settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': cfg.get('sql-database'), 'USER': cfg.get('sql-username'), 'PASSWORD': cfg.get('sql-password'), 'OPTIONS': { 'charset': 'latin1', } } }, MIDDLEWARE_CLASSES = (), DOWNLOAD_DIRECTORY = cfg.get('download-directory', '/var/tmp'), ) if django.VERSION >= (1, 7): from django.apps import apps apps.populate(settings.INSTALLED_APPS)