我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用django.apps.apps.populate()。
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 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 reinit_plugin(name, upmate: bool=False): # pragma: no cover """ Reinitialize gitmate with plugin and upmate, if specified. """ app_name = 'gitmate_' + name app_config_name = 'plugins.{}.apps.{}Config'.format( app_name, snake_case_to_camel_case(app_name)) if app_config_name in settings.INSTALLED_APPS: return settings.GITMATE_PLUGINS += [name] settings.INSTALLED_APPS += [app_config_name] # To load the new app let's reset app_configs, the dictionary # with the configuration of loaded apps apps.app_configs = OrderedDict() # set ready to false so that populate will work apps.ready = False # re-initialize them all apps.populate(settings.INSTALLED_APPS) # migrate the models management.call_command('migrate', app_name, interactive=False) # upmate the plugins, if specified if upmate is True: management.call_command('upmate', interactive=False)
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 get_model(app_label, model_name): """ Fetches a Django model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry not being ready yet. Raises LookupError if model isn't found. """ try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If this function is called while `apps.populate()` is # loading models, ensure that the module that defines the # target model has been imported and try looking the model up # in the app registry. This effectively emulates # `from path.to.app.models import Model` where we use # `Model = get_model('app', 'Model')` instead. app_config = apps.get_app_config(app_label) # `app_config.import_models()` cannot be used here because it # would interfere with `apps.populate()`. import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) # In order to account for case-insensitivity of model_name, # look up the model through a private API of the app registry. return apps.get_registered_model(app_label, model_name) else: # This must be a different case (e.g. the model really doesn't # exist). We just re-raise the exception. raise
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)
def read_config(self): global rpki # pylint: disable=W0602 try: cfg = rpki.config.parser(self.cfg_file, "myrpki") cfg.set_global_flags() except IOError, e: sys.exit("%s: %s" % (e.strerror, e.filename)) self.histfile = cfg.get("history_file", os.path.expanduser("~/.rpkic_history")) self.autosync = cfg.getboolean("autosync", True, section = "rpkic") import django from django.conf import settings settings.configure( DATABASES = { "default" : { "ENGINE" : "django.db.backends.mysql", "NAME" : cfg.get("sql-database", section = "irdbd"), "USER" : cfg.get("sql-username", section = "irdbd"), "PASSWORD" : cfg.get("sql-password", section = "irdbd"), "HOST" : "", "PORT" : "", "OPTIONS" : { "init_command": "SET storage_engine=INNODB", "charset" : "latin1" }}}, INSTALLED_APPS = ("rpki.irdb",), MIDDLEWARE_CLASSES = (), # API change, feh ) if django.VERSION >= (1, 7): # API change, feh from django.apps import apps apps.populate(settings.INSTALLED_APPS) import rpki.irdb # pylint: disable=W0621 try: rpki.irdb.models.ca_certificate_lifetime = rpki.sundial.timedelta.parse( cfg.get("bpki_ca_certificate_lifetime", section = "rpkic")) except rpki.config.ConfigParser.Error: pass try: rpki.irdb.models.ee_certificate_lifetime = rpki.sundial.timedelta.parse( cfg.get("bpki_ee_certificate_lifetime", section = "rpkic")) except rpki.config.ConfigParser.Error: pass try: rpki.irdb.models.crl_interval = rpki.sundial.timedelta.parse( cfg.get("bpki_crl_interval", section = "rpkic")) except rpki.config.ConfigParser.Error: pass import django.core.management django.core.management.call_command("syncdb", verbosity = 0, load_initial_data = False) self.zoo = rpki.irdb.Zookeeper(cfg = cfg, handle = self.handle, logstream = sys.stdout)