2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
import glob
|
2008-12-01 10:21:33 +08:00
|
|
|
import gzip
|
2013-06-02 16:40:54 +08:00
|
|
|
import os
|
2013-02-24 03:34:59 +08:00
|
|
|
import warnings
|
2008-12-01 10:21:33 +08:00
|
|
|
import zipfile
|
2015-01-28 20:35:27 +08:00
|
|
|
from itertools import product
|
2008-12-01 10:21:33 +08:00
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2009-12-22 23:18:51 +08:00
|
|
|
from django.conf import settings
|
|
|
|
from django.core import serializers
|
2014-10-31 01:38:47 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2012-06-07 16:31:08 +08:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
2008-12-01 10:21:33 +08:00
|
|
|
from django.core.management.color import no_style
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db import (
|
|
|
|
DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connections, router,
|
|
|
|
transaction,
|
|
|
|
)
|
2013-11-02 04:15:41 +08:00
|
|
|
from django.utils import lru_cache
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils._os import upath
|
2012-07-21 16:00:10 +08:00
|
|
|
from django.utils.encoding import force_text
|
2013-11-02 04:15:41 +08:00
|
|
|
from django.utils.functional import cached_property
|
2015-06-13 18:20:05 +08:00
|
|
|
from django.utils.glob import glob_escape
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2008-12-01 10:20:59 +08:00
|
|
|
try:
|
|
|
|
import bz2
|
|
|
|
has_bz2 = True
|
|
|
|
except ImportError:
|
|
|
|
has_bz2 = False
|
|
|
|
|
2012-09-30 20:34:13 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
class Command(BaseCommand):
|
|
|
|
help = 'Installs the named fixture(s) in the database.'
|
2016-03-29 06:33:29 +08:00
|
|
|
missing_args_message = (
|
|
|
|
"No database fixture specified. Please provide the path of at least "
|
|
|
|
"one fixture in the command line."
|
|
|
|
)
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2014-06-07 04:39:33 +08:00
|
|
|
def add_arguments(self, parser):
|
2016-03-29 06:33:29 +08:00
|
|
|
parser.add_argument('args', metavar='fixture', nargs='+', help='Fixture labels.')
|
|
|
|
parser.add_argument(
|
|
|
|
'--database', action='store', dest='database', default=DEFAULT_DB_ALIAS,
|
|
|
|
help='Nominates a specific database to load fixtures into. Defaults to the "default" database.',
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'--app', action='store', dest='app_label', default=None,
|
|
|
|
help='Only look for fixtures in the specified app.',
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'--ignorenonexistent', '-i', action='store_true', dest='ignore', default=False,
|
2014-06-07 04:39:33 +08:00
|
|
|
help='Ignores entries in the serialized data for fields that do not '
|
2016-03-29 06:33:29 +08:00
|
|
|
'currently exist on the model.',
|
|
|
|
)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
def handle(self, *fixture_labels, **options):
|
2012-09-30 20:34:13 +08:00
|
|
|
|
2016-03-03 10:01:36 +08:00
|
|
|
self.ignore = options['ignore']
|
|
|
|
self.using = options['database']
|
|
|
|
self.app_label = options['app_label']
|
|
|
|
self.verbosity = options['verbosity']
|
2008-10-02 20:57:13 +08:00
|
|
|
|
2014-03-21 21:21:43 +08:00
|
|
|
with transaction.atomic(using=self.using):
|
2013-03-08 18:35:15 +08:00
|
|
|
self.loaddata(fixture_labels)
|
|
|
|
|
|
|
|
# Close the DB connection -- unless we're still in a transaction. This
|
|
|
|
# is required as a workaround for an edge case in MySQL: if the same
|
|
|
|
# connection is used to create tables, load data, and query, the query
|
|
|
|
# can return incorrect results. See Django #7572, MySQL #37735.
|
|
|
|
if transaction.get_autocommit(self.using):
|
|
|
|
connections[self.using].close()
|
|
|
|
|
|
|
|
def loaddata(self, fixture_labels):
|
|
|
|
connection = connections[self.using]
|
2008-10-02 20:57:13 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
# Keep a count of the installed objects and fixtures
|
2012-11-10 09:17:43 +08:00
|
|
|
self.fixture_count = 0
|
|
|
|
self.loaded_object_count = 0
|
|
|
|
self.fixture_object_count = 0
|
|
|
|
self.models = set()
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
self.serialization_formats = serializers.get_public_serializer_formats()
|
2014-04-19 00:40:58 +08:00
|
|
|
# Forcing binary mode may be revisited after dropping Python 2 support (see #22399)
|
2013-06-02 16:40:54 +08:00
|
|
|
self.compression_formats = {
|
2014-04-19 00:40:58 +08:00
|
|
|
None: (open, 'rb'),
|
|
|
|
'gz': (gzip.GzipFile, 'rb'),
|
|
|
|
'zip': (SingleZipReader, 'r'),
|
2008-11-25 04:42:09 +08:00
|
|
|
}
|
2008-12-01 10:20:59 +08:00
|
|
|
if has_bz2:
|
2014-04-19 00:40:58 +08:00
|
|
|
self.compression_formats['bz2'] = (bz2.BZ2File, 'r')
|
2008-11-25 04:42:09 +08:00
|
|
|
|
2015-12-30 00:29:11 +08:00
|
|
|
# Django's test suite repeatedly tries to load initial_data fixtures
|
|
|
|
# from apps that don't have any fixtures. Because disabling constraint
|
|
|
|
# checks can be expensive on some database (especially MSSQL), bail
|
|
|
|
# out early if no fixtures are found.
|
|
|
|
for fixture_label in fixture_labels:
|
|
|
|
if self.find_fixtures(fixture_label):
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
return
|
|
|
|
|
2013-03-08 18:35:15 +08:00
|
|
|
with connection.constraint_checks_disabled():
|
|
|
|
for fixture_label in fixture_labels:
|
2013-06-02 16:40:54 +08:00
|
|
|
self.load_label(fixture_label)
|
2013-03-08 18:35:15 +08:00
|
|
|
|
|
|
|
# Since we disabled constraint checks, we must manually check for
|
|
|
|
# any invalid keys that might have been added
|
|
|
|
table_names = [model._meta.db_table for model in self.models]
|
2012-01-15 01:26:32 +08:00
|
|
|
try:
|
2013-03-08 18:35:15 +08:00
|
|
|
connection.check_constraints(table_names=table_names)
|
2012-06-07 16:31:08 +08:00
|
|
|
except Exception as e:
|
2013-03-08 18:35:15 +08:00
|
|
|
e.args = ("Problem installing fixtures: %s" % e,)
|
2012-06-07 16:31:08 +08:00
|
|
|
raise
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-13 22:36:40 +08:00
|
|
|
# If we found even one object in a fixture, we need to reset the
|
2008-06-08 16:21:18 +08:00
|
|
|
# database sequences.
|
2012-11-10 09:17:43 +08:00
|
|
|
if self.loaded_object_count > 0:
|
|
|
|
sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models)
|
2007-08-16 14:06:55 +08:00
|
|
|
if sequence_sql:
|
2012-11-10 09:17:43 +08:00
|
|
|
if self.verbosity >= 2:
|
2010-06-05 13:26:04 +08:00
|
|
|
self.stdout.write("Resetting sequences\n")
|
2014-01-09 23:05:15 +08:00
|
|
|
with connection.cursor() as cursor:
|
|
|
|
for line in sequence_sql:
|
|
|
|
cursor.execute(line)
|
2008-10-02 20:57:13 +08:00
|
|
|
|
2012-11-10 09:17:43 +08:00
|
|
|
if self.verbosity >= 1:
|
2016-03-02 03:29:02 +08:00
|
|
|
if self.fixture_object_count == self.loaded_object_count:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.stdout.write(
|
|
|
|
"Installed %d object(s) from %d fixture(s)"
|
|
|
|
% (self.loaded_object_count, self.fixture_count)
|
|
|
|
)
|
2011-10-29 22:47:45 +08:00
|
|
|
else:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.stdout.write(
|
|
|
|
"Installed %d object(s) (of %d) from %d fixture(s)"
|
|
|
|
% (self.loaded_object_count, self.fixture_object_count, self.fixture_count)
|
|
|
|
)
|
2013-06-02 16:40:54 +08:00
|
|
|
|
|
|
|
def load_label(self, fixture_label):
|
|
|
|
"""
|
|
|
|
Loads fixtures files for a given label.
|
|
|
|
"""
|
2015-04-14 01:27:14 +08:00
|
|
|
show_progress = self.verbosity >= 3
|
2013-06-02 16:40:54 +08:00
|
|
|
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))
|
2014-04-19 00:40:58 +08:00
|
|
|
open_method, mode = self.compression_formats[cmp_fmt]
|
|
|
|
fixture = open_method(fixture_file, mode)
|
2013-06-02 16:40:54 +08:00
|
|
|
try:
|
|
|
|
self.fixture_count += 1
|
|
|
|
objects_in_fixture = 0
|
|
|
|
loaded_objects_in_fixture = 0
|
|
|
|
if self.verbosity >= 2:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.stdout.write(
|
|
|
|
"Installing %s fixture '%s' from %s."
|
|
|
|
% (ser_fmt, fixture_name, humanize(fixture_dir))
|
|
|
|
)
|
2013-06-02 16:40:54 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
objects = serializers.deserialize(
|
|
|
|
ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore,
|
|
|
|
)
|
2013-06-02 16:40:54 +08:00
|
|
|
|
|
|
|
for obj in objects:
|
|
|
|
objects_in_fixture += 1
|
2015-02-19 15:27:58 +08:00
|
|
|
if router.allow_migrate_model(self.using, obj.object.__class__):
|
2013-06-02 16:40:54 +08:00
|
|
|
loaded_objects_in_fixture += 1
|
|
|
|
self.models.add(obj.object.__class__)
|
|
|
|
try:
|
|
|
|
obj.save(using=self.using)
|
2015-04-14 01:27:14 +08:00
|
|
|
if show_progress:
|
|
|
|
self.stdout.write(
|
|
|
|
'\rProcessed %i object(s).' % loaded_objects_in_fixture,
|
|
|
|
ending=''
|
|
|
|
)
|
2013-06-02 16:40:54 +08:00
|
|
|
except (DatabaseError, IntegrityError) as e:
|
|
|
|
e.args = ("Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
|
2013-10-20 07:33:10 +08:00
|
|
|
'app_label': obj.object._meta.app_label,
|
|
|
|
'object_name': obj.object._meta.object_name,
|
|
|
|
'pk': obj.object.pk,
|
|
|
|
'error_msg': force_text(e)
|
2013-10-18 17:02:43 +08:00
|
|
|
},)
|
2013-06-02 16:40:54 +08:00
|
|
|
raise
|
2015-04-14 01:27:14 +08:00
|
|
|
if objects and show_progress:
|
|
|
|
self.stdout.write('') # add a newline after progress indicator
|
2013-06-02 16:40:54 +08:00
|
|
|
self.loaded_object_count += loaded_objects_in_fixture
|
|
|
|
self.fixture_object_count += objects_in_fixture
|
|
|
|
except Exception as e:
|
|
|
|
if not isinstance(e, CommandError):
|
|
|
|
e.args = ("Problem installing fixture '%s': %s" % (fixture_file, e),)
|
|
|
|
raise
|
|
|
|
finally:
|
|
|
|
fixture.close()
|
|
|
|
|
2013-02-24 03:34:59 +08:00
|
|
|
# Warn if the fixture we loaded contains 0 objects.
|
2013-06-02 16:40:54 +08:00
|
|
|
if objects_in_fixture == 0:
|
2013-02-24 03:34:59 +08:00
|
|
|
warnings.warn(
|
|
|
|
"No fixture data found for '%s'. (File format may be "
|
|
|
|
"invalid.)" % fixture_name,
|
|
|
|
RuntimeWarning
|
|
|
|
)
|
2013-06-02 16:40:54 +08:00
|
|
|
|
2013-11-02 04:15:41 +08:00
|
|
|
@lru_cache.lru_cache(maxsize=None)
|
|
|
|
def find_fixtures(self, fixture_label):
|
2013-06-02 16:40:54 +08:00
|
|
|
"""
|
|
|
|
Finds fixture files for a given label.
|
|
|
|
"""
|
|
|
|
fixture_name, ser_fmt, cmp_fmt = self.parse_name(fixture_label)
|
|
|
|
databases = [self.using, None]
|
|
|
|
cmp_fmts = list(self.compression_formats.keys()) if cmp_fmt is None else [cmp_fmt]
|
|
|
|
ser_fmts = serializers.get_public_serializer_formats() if ser_fmt is None else [ser_fmt]
|
|
|
|
|
|
|
|
if self.verbosity >= 2:
|
|
|
|
self.stdout.write("Loading '%s' fixtures..." % fixture_name)
|
2012-11-10 09:17:43 +08:00
|
|
|
|
2013-12-06 05:55:33 +08:00
|
|
|
if os.path.isabs(fixture_name):
|
2013-06-02 16:40:54 +08:00
|
|
|
fixture_dirs = [os.path.dirname(fixture_name)]
|
|
|
|
fixture_name = os.path.basename(fixture_name)
|
2012-11-10 09:17:43 +08:00
|
|
|
else:
|
2013-06-02 16:40:54 +08:00
|
|
|
fixture_dirs = self.fixture_dirs
|
2014-10-08 01:53:19 +08:00
|
|
|
if os.path.sep in os.path.normpath(fixture_name):
|
2013-12-06 05:55:33 +08:00
|
|
|
fixture_dirs = [os.path.join(dir_, os.path.dirname(fixture_name))
|
|
|
|
for dir_ in fixture_dirs]
|
|
|
|
fixture_name = os.path.basename(fixture_name)
|
2012-11-10 09:17:43 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
suffixes = (
|
|
|
|
'.'.join(ext for ext in combo if ext)
|
|
|
|
for combo in product(databases, ser_fmts, cmp_fmts)
|
|
|
|
)
|
2013-06-02 16:40:54 +08:00
|
|
|
targets = set('.'.join((fixture_name, suffix)) for suffix in suffixes)
|
2012-11-10 09:17:43 +08:00
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
fixture_files = []
|
|
|
|
for fixture_dir in fixture_dirs:
|
2012-11-10 09:17:43 +08:00
|
|
|
if self.verbosity >= 2:
|
2013-06-02 16:40:54 +08:00
|
|
|
self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir))
|
|
|
|
fixture_files_in_dir = []
|
2015-06-13 18:20:05 +08:00
|
|
|
path = os.path.join(fixture_dir, fixture_name)
|
|
|
|
for candidate in glob.iglob(glob_escape(path) + '*'):
|
2013-06-02 16:40:54 +08:00
|
|
|
if os.path.basename(candidate) in targets:
|
|
|
|
# Save the fixture_dir and fixture_name for future error messages.
|
|
|
|
fixture_files_in_dir.append((candidate, fixture_dir, fixture_name))
|
|
|
|
|
|
|
|
if self.verbosity >= 2 and not fixture_files_in_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(
|
2013-10-20 07:33:10 +08:00
|
|
|
"Multiple fixtures named '%s' in %s. Aborting." %
|
|
|
|
(fixture_name, humanize(fixture_dir)))
|
2013-06-02 16:40:54 +08:00
|
|
|
fixture_files.extend(fixture_files_in_dir)
|
|
|
|
|
2014-12-27 02:23:38 +08:00
|
|
|
if not fixture_files:
|
2016-01-03 03:11:18 +08:00
|
|
|
raise CommandError("No fixture named '%s' found." % fixture_name)
|
2013-06-02 16:40:54 +08:00
|
|
|
|
|
|
|
return fixture_files
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def fixture_dirs(self):
|
|
|
|
"""
|
|
|
|
Return a list of fixture directories.
|
|
|
|
|
|
|
|
The list contains the 'fixtures' subdirectory of each installed
|
|
|
|
application, if it exists, the directories in FIXTURE_DIRS, and the
|
|
|
|
current directory.
|
|
|
|
"""
|
|
|
|
dirs = []
|
2014-10-31 01:38:47 +08:00
|
|
|
fixture_dirs = settings.FIXTURE_DIRS
|
|
|
|
if len(fixture_dirs) != len(set(fixture_dirs)):
|
|
|
|
raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.")
|
2013-12-24 19:25:17 +08:00
|
|
|
for app_config in apps.get_app_configs():
|
2014-10-31 01:38:47 +08:00
|
|
|
app_label = app_config.label
|
2014-04-21 18:25:43 +08:00
|
|
|
app_dir = os.path.join(app_config.path, 'fixtures')
|
2014-10-31 01:38:47 +08:00
|
|
|
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)
|
|
|
|
)
|
|
|
|
|
|
|
|
if self.app_label and app_label != self.app_label:
|
|
|
|
continue
|
2014-04-21 18:25:43 +08:00
|
|
|
if os.path.isdir(app_dir):
|
|
|
|
dirs.append(app_dir)
|
2014-10-31 01:38:47 +08:00
|
|
|
dirs.extend(list(fixture_dirs))
|
2013-06-02 16:40:54 +08:00
|
|
|
dirs.append('')
|
2013-06-03 19:18:16 +08:00
|
|
|
dirs = [upath(os.path.abspath(os.path.realpath(d))) for d in dirs]
|
2013-06-02 16:40:54 +08:00
|
|
|
return dirs
|
|
|
|
|
|
|
|
def parse_name(self, fixture_name):
|
|
|
|
"""
|
|
|
|
Splits fixture name in name, serialization format, compression format.
|
|
|
|
"""
|
|
|
|
parts = fixture_name.rsplit('.', 2)
|
|
|
|
|
|
|
|
if len(parts) > 1 and parts[-1] in self.compression_formats:
|
|
|
|
cmp_fmt = parts[-1]
|
|
|
|
parts = parts[:-1]
|
2012-11-10 09:17:43 +08:00
|
|
|
else:
|
2013-06-02 16:40:54 +08:00
|
|
|
cmp_fmt = None
|
2012-11-10 09:17:43 +08:00
|
|
|
|
2013-11-18 21:05:59 +08:00
|
|
|
if len(parts) > 1:
|
|
|
|
if parts[-1] in self.serialization_formats:
|
|
|
|
ser_fmt = parts[-1]
|
|
|
|
parts = parts[:-1]
|
|
|
|
else:
|
|
|
|
raise CommandError(
|
|
|
|
"Problem installing fixture '%s': %s is not a known "
|
|
|
|
"serialization format." % (''.join(parts[:-1]), parts[-1]))
|
2012-11-10 09:17:43 +08:00
|
|
|
else:
|
2013-06-02 16:40:54 +08:00
|
|
|
ser_fmt = None
|
2012-11-10 09:17:43 +08:00
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
name = '.'.join(parts)
|
2013-05-18 23:51:14 +08:00
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
return name, ser_fmt, cmp_fmt
|
2012-11-10 09:17:43 +08:00
|
|
|
|
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
class SingleZipReader(zipfile.ZipFile):
|
2012-11-10 09:17:43 +08:00
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
zipfile.ZipFile.__init__(self, *args, **kwargs)
|
|
|
|
if len(self.namelist()) != 1:
|
|
|
|
raise ValueError("Zip-compressed fixtures must contain one file.")
|
|
|
|
|
|
|
|
def read(self):
|
|
|
|
return zipfile.ZipFile.read(self, self.namelist()[0])
|
|
|
|
|
|
|
|
|
|
|
|
def humanize(dirname):
|
|
|
|
return "'%s'" % dirname if dirname else 'absolute path'
|