def get_app_errors(): try: return app_cache.app_errors except AttributeError: app_cache.populate_models() app_cache.app_errors = {} return app_cache.app_errors
def __init__(self, stream_or_string, **options): """ Init this serializer given a stream or a string """ self.options = options if isinstance(stream_or_string, six.string_types): self.stream = six.StringIO(stream_or_string) else: self.stream = stream_or_string # Make sure the app cache is loaded before deserialization starts # (otherwise subclass calls to get_model() and friends might fail...) app_cache.populate_models()
def handle(self, *app_labels, **options): from django.apps import app_cache if not app_labels: raise CommandError('Enter at least one appname.') # Populate models and don't use only_with_models_module=True when # calling get_app_config() to tell apart missing apps from apps # without a model module -- which can't be supported with the legacy # API since it passes the models module to handle_app(). app_cache.populate_models() try: app_configs = [app_cache.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: if app_config.models_module is None: raise CommandError( "AppCommand cannot handle app %r because it doesn't have " "a models module." % app_config.label) app_output = self.handle_app(app_config.models_module, **options) if app_output: output.append(app_output) return '\n'.join(output)
def setup(verbosity, test_labels): import django from django.apps import app_cache from django.conf import settings from django.test import TransactionTestCase, TestCase print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the ALWAYS_INSTALLED_APPS. with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', DeprecationWarning) app_cache.populate_models() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.') if bits[:2] == ['django', 'contrib']: bits = bits[:3] else: bits = bits[:1] test_labels_set.add('.'.join(bits)) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: match = lambda label: ( module_label == label or # exact match module_label.startswith(label + '.') # ancestor match ) module_found_in_labels = any(match(l) for l in test_labels_set) if module_found_in_labels: if verbosity >= 2: print("Importing application %s" % module_name) # HACK. app_cache._begin_with_app(module_label) if module_label not in settings.INSTALLED_APPS: settings.INSTALLED_APPS.append(module_label) return state
def Deserializer(object_list, **options): """ Deserialize simple Python objects back into Django ORM instances. It's expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor """ db = options.pop('using', DEFAULT_DB_ALIAS) ignore = options.pop('ignorenonexistent', False) app_cache.populate_models() for d in object_list: # Look up the model and starting build a dict of data for it. Model = _get_model(d["model"]) data = {} if 'pk' in d: data[Model._meta.pk.attname] = Model._meta.pk.to_python(d.get("pk", None)) m2m_data = {} model_fields = Model._meta.get_all_field_names() # Handle each field for (field_name, field_value) in six.iteritems(d["fields"]): if ignore and field_name not in model_fields: # skip fields no longer on model continue if isinstance(field_value, str): field_value = smart_text(field_value, options.get("encoding", settings.DEFAULT_CHARSET), strings_only=True) field = Model._meta.get_field(field_name) # Handle M2M relations if field.rel and isinstance(field.rel, models.ManyToManyRel): if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): def m2m_convert(value): if hasattr(value, '__iter__') and not isinstance(value, six.text_type): return field.rel.to._default_manager.db_manager(db).get_by_natural_key(*value).pk else: return smart_text(field.rel.to._meta.pk.to_python(value)) else: m2m_convert = lambda v: smart_text(field.rel.to._meta.pk.to_python(v)) m2m_data[field.name] = [m2m_convert(pk) for pk in field_value] # Handle FK fields elif field.rel and isinstance(field.rel, models.ManyToOneRel): if field_value is not None: if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): if hasattr(field_value, '__iter__') and not isinstance(field_value, six.text_type): obj = field.rel.to._default_manager.db_manager(db).get_by_natural_key(*field_value) value = getattr(obj, field.rel.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value if field.rel.to._meta.pk.rel: value = value.pk else: value = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) data[field.attname] = value else: data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) else: data[field.attname] = None # Handle all other fields else: data[field.name] = field.to_python(field_value) obj = base.build_instance(Model, data, db) yield base.DeserializedObject(obj, m2m_data)
def __init__(self): # Before we can introspect models, they need the app cache to be fully # loaded so that inter-relations are set up correctly. app_cache.populate_models()