diff options
| author | django-bot <ops@djangoproject.com> | 2022-02-03 20:24:19 +0100 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2022-02-07 20:37:05 +0100 |
| commit | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch) | |
| tree | f0506b668a013d0063e5fba3dbf4863b466713ba /django/core/management/commands/loaddata.py | |
| parent | f68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff) | |
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'django/core/management/commands/loaddata.py')
| -rw-r--r-- | django/core/management/commands/loaddata.py | 163 |
1 files changed, 102 insertions, 61 deletions
diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 20428f9f10..38a2818d5c 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -15,64 +15,82 @@ from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.core.management.utils import parse_apps_and_model_labels from django.db import ( - DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connections, router, + DEFAULT_DB_ALIAS, + DatabaseError, + IntegrityError, + connections, + router, transaction, ) from django.utils.functional import cached_property try: import bz2 + has_bz2 = True except ImportError: has_bz2 = False try: import lzma + has_lzma = True except ImportError: has_lzma = False -READ_STDIN = '-' +READ_STDIN = "-" class Command(BaseCommand): - help = 'Installs the named fixture(s) in the database.' + help = "Installs the named fixture(s) in the database." missing_args_message = ( "No database fixture specified. Please provide the path of at least " "one fixture in the command line." ) def add_arguments(self, parser): - parser.add_argument('args', metavar='fixture', nargs='+', help='Fixture labels.') parser.add_argument( - '--database', default=DEFAULT_DB_ALIAS, + "args", metavar="fixture", nargs="+", help="Fixture labels." + ) + parser.add_argument( + "--database", + default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load fixtures into. Defaults to the "default" database.', ) parser.add_argument( - '--app', dest='app_label', - help='Only look for fixtures in the specified app.', + "--app", + dest="app_label", + help="Only look for fixtures in the specified app.", ) parser.add_argument( - '--ignorenonexistent', '-i', action='store_true', dest='ignore', - help='Ignores entries in the serialized data for fields that do not ' - 'currently exist on the model.', + "--ignorenonexistent", + "-i", + action="store_true", + dest="ignore", + help="Ignores entries in the serialized data for fields that do not " + "currently exist on the model.", ) parser.add_argument( - '-e', '--exclude', action='append', default=[], - help='An app_label or app_label.ModelName to exclude. Can be used multiple times.', + "-e", + "--exclude", + action="append", + default=[], + help="An app_label or app_label.ModelName to exclude. Can be used multiple times.", ) parser.add_argument( - '--format', - help='Format of serialized data when reading from stdin.', + "--format", + help="Format of serialized data when reading from stdin.", ) def handle(self, *fixture_labels, **options): - self.ignore = options['ignore'] - self.using = options['database'] - self.app_label = options['app_label'] - self.verbosity = options['verbosity'] - self.excluded_models, self.excluded_apps = parse_apps_and_model_labels(options['exclude']) - self.format = options['format'] + self.ignore = options["ignore"] + self.using = options["database"] + self.app_label = options["app_label"] + self.verbosity = options["verbosity"] + self.excluded_models, self.excluded_apps = parse_apps_and_model_labels( + options["exclude"] + ) + self.format = options["format"] with transaction.atomic(using=self.using): self.loaddata(fixture_labels) @@ -89,16 +107,16 @@ class Command(BaseCommand): """A dict mapping format names to (open function, mode arg) tuples.""" # Forcing binary mode may be revisited after dropping Python 2 support (see #22399) compression_formats = { - None: (open, 'rb'), - 'gz': (gzip.GzipFile, 'rb'), - 'zip': (SingleZipReader, 'r'), - 'stdin': (lambda *args: sys.stdin, None), + None: (open, "rb"), + "gz": (gzip.GzipFile, "rb"), + "zip": (SingleZipReader, "r"), + "stdin": (lambda *args: sys.stdin, None), } if has_bz2: - compression_formats['bz2'] = (bz2.BZ2File, 'r') + compression_formats["bz2"] = (bz2.BZ2File, "r") if has_lzma: - compression_formats['lzma'] = (lzma.LZMAFile, 'r') - compression_formats['xz'] = (lzma.LZMAFile, 'r') + compression_formats["lzma"] = (lzma.LZMAFile, "r") + compression_formats["xz"] = (lzma.LZMAFile, "r") return compression_formats def reset_sequences(self, connection, models): @@ -106,7 +124,7 @@ class Command(BaseCommand): sequence_sql = connection.ops.sequence_reset_sql(no_style(), models) if sequence_sql: if self.verbosity >= 2: - self.stdout.write('Resetting sequences') + self.stdout.write("Resetting sequences") with connection.cursor() as cursor: for line in sequence_sql: cursor.execute(line) @@ -162,14 +180,18 @@ class Command(BaseCommand): else: self.stdout.write( "Installed %d object(s) (of %d) from %d fixture(s)" - % (self.loaded_object_count, self.fixture_object_count, self.fixture_count) + % ( + self.loaded_object_count, + self.fixture_object_count, + self.fixture_count, + ) ) def save_obj(self, obj): """Save an object if permitted.""" if ( - obj.object._meta.app_config in self.excluded_apps or - type(obj.object) in self.excluded_models + obj.object._meta.app_config in self.excluded_apps + or type(obj.object) in self.excluded_models ): return False saved = False @@ -180,11 +202,14 @@ class Command(BaseCommand): obj.save(using=self.using) # psycopg2 raises ValueError if data contains NUL chars. except (DatabaseError, IntegrityError, ValueError) as e: - e.args = ('Could not load %(object_label)s(pk=%(pk)s): %(error_msg)s' % { - 'object_label': obj.object._meta.label, - 'pk': obj.object.pk, - 'error_msg': e, - },) + e.args = ( + "Could not load %(object_label)s(pk=%(pk)s): %(error_msg)s" + % { + "object_label": obj.object._meta.label, + "pk": obj.object.pk, + "error_msg": e, + }, + ) raise if obj.deferred_fields: self.objs_with_deferred_fields.append(obj) @@ -193,7 +218,9 @@ class Command(BaseCommand): def load_label(self, fixture_label): """Load fixtures files for a given label.""" show_progress = self.verbosity >= 3 - for fixture_file, fixture_dir, fixture_name in self.find_fixtures(fixture_label): + for fixture_file, fixture_dir, fixture_name in self.find_fixtures( + fixture_label + ): _, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file)) open_method, mode = self.compression_formats[cmp_fmt] fixture = open_method(fixture_file, mode) @@ -207,7 +234,10 @@ class Command(BaseCommand): ) try: objects = serializers.deserialize( - ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore, + ser_fmt, + fixture, + using=self.using, + ignorenonexistent=self.ignore, handle_forward_references=True, ) @@ -217,12 +247,14 @@ class Command(BaseCommand): loaded_objects_in_fixture += 1 if show_progress: self.stdout.write( - '\rProcessed %i object(s).' % loaded_objects_in_fixture, - ending='' + "\rProcessed %i object(s)." % loaded_objects_in_fixture, + ending="", ) except Exception as e: if not isinstance(e, CommandError): - e.args = ("Problem installing fixture '%s': %s" % (fixture_file, e),) + e.args = ( + "Problem installing fixture '%s': %s" % (fixture_file, e), + ) raise finally: fixture.close() @@ -236,7 +268,7 @@ class Command(BaseCommand): warnings.warn( "No fixture data found for '%s'. (File format may be " "invalid.)" % fixture_name, - RuntimeWarning + RuntimeWarning, ) def get_fixture_name_and_dirs(self, fixture_name): @@ -254,16 +286,18 @@ class Command(BaseCommand): cmp_fmts = self.compression_formats if cmp_fmt is None else [cmp_fmt] ser_fmts = self.serialization_formats if ser_fmt is None else [ser_fmt] return { - '%s.%s' % ( + "%s.%s" + % ( fixture_name, - '.'.join([ext for ext in combo if ext]), - ) for combo in product(databases, ser_fmts, cmp_fmts) + ".".join([ext for ext in combo if ext]), + ) + for combo in product(databases, ser_fmts, cmp_fmts) } def find_fixture_files_in_dir(self, fixture_dir, fixture_name, targets): fixture_files_in_dir = [] path = os.path.join(fixture_dir, fixture_name) - for candidate in glob.iglob(glob.escape(path) + '*'): + for candidate in glob.iglob(glob.escape(path) + "*"): if os.path.basename(candidate) in targets: # Save the fixture_dir and fixture_name for future error # messages. @@ -287,18 +321,22 @@ class Command(BaseCommand): if self.verbosity >= 2: self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir)) fixture_files_in_dir = self.find_fixture_files_in_dir( - fixture_dir, fixture_name, targets, + fixture_dir, + fixture_name, + targets, ) if self.verbosity >= 2 and not fixture_files_in_dir: - self.stdout.write("No fixture '%s' in %s." % - (fixture_name, humanize(fixture_dir))) + self.stdout.write( + "No fixture '%s' in %s." % (fixture_name, humanize(fixture_dir)) + ) # Check kept for backwards-compatibility; it isn't clear why # duplicates are only allowed in different directories. if len(fixture_files_in_dir) > 1: raise CommandError( - "Multiple fixtures named '%s' in %s. Aborting." % - (fixture_name, humanize(fixture_dir))) + "Multiple fixtures named '%s' in %s. Aborting." + % (fixture_name, humanize(fixture_dir)) + ) fixture_files.extend(fixture_files_in_dir) if not fixture_files: @@ -321,11 +359,12 @@ class Command(BaseCommand): raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.") for app_config in apps.get_app_configs(): app_label = app_config.label - app_dir = os.path.join(app_config.path, 'fixtures') + app_dir = os.path.join(app_config.path, "fixtures") if app_dir in fixture_dirs: raise ImproperlyConfigured( "'%s' is a default fixture directory for the '%s' app " - "and cannot be listed in settings.FIXTURE_DIRS." % (app_dir, app_label) + "and cannot be listed in settings.FIXTURE_DIRS." + % (app_dir, app_label) ) if self.app_label and app_label != self.app_label: @@ -333,7 +372,7 @@ class Command(BaseCommand): if os.path.isdir(app_dir): dirs.append(app_dir) dirs.extend(fixture_dirs) - dirs.append('') + dirs.append("") return [os.path.realpath(d) for d in dirs] def parse_name(self, fixture_name): @@ -342,10 +381,12 @@ class Command(BaseCommand): """ if fixture_name == READ_STDIN: if not self.format: - raise CommandError('--format must be specified when reading from stdin.') - return READ_STDIN, self.format, 'stdin' + raise CommandError( + "--format must be specified when reading from stdin." + ) + return READ_STDIN, self.format, "stdin" - parts = fixture_name.rsplit('.', 2) + parts = fixture_name.rsplit(".", 2) if len(parts) > 1 and parts[-1] in self.compression_formats: cmp_fmt = parts[-1] @@ -360,17 +401,17 @@ class Command(BaseCommand): else: raise CommandError( "Problem installing fixture '%s': %s is not a known " - "serialization format." % ('.'.join(parts[:-1]), parts[-1])) + "serialization format." % (".".join(parts[:-1]), parts[-1]) + ) else: ser_fmt = None - name = '.'.join(parts) + name = ".".join(parts) return name, ser_fmt, cmp_fmt class SingleZipReader(zipfile.ZipFile): - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if len(self.namelist()) != 1: @@ -381,4 +422,4 @@ class SingleZipReader(zipfile.ZipFile): def humanize(dirname): - return "'%s'" % dirname if dirname else 'absolute path' + return "'%s'" % dirname if dirname else "absolute path" |
