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
|
|
|
|
from optparse import make_option
|
|
|
|
|
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
|
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
|
2011-09-22 12:30:20 +08:00
|
|
|
from django.db import (connections, router, transaction, DEFAULT_DB_ALIAS,
|
|
|
|
IntegrityError, DatabaseError)
|
2013-11-02 04:15:41 +08:00
|
|
|
from django.utils import lru_cache
|
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
|
2013-06-03 19:18:16 +08:00
|
|
|
from django.utils._os import upath
|
2012-03-31 16:24:29 +08:00
|
|
|
from itertools import product
|
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.'
|
2007-09-10 05:57:59 +08:00
|
|
|
args = "fixture [fixture ...]"
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
option_list = BaseCommand.option_list + (
|
|
|
|
make_option('--database', action='store', dest='database',
|
|
|
|
default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load '
|
|
|
|
'fixtures into. Defaults to the "default" database.'),
|
2014-02-09 20:22:29 +08:00
|
|
|
make_option('--app', action='store', dest='app_label',
|
|
|
|
default=None, help='Only look for fixtures in the specified app.'),
|
2012-09-30 20:34:13 +08:00
|
|
|
make_option('--ignorenonexistent', '-i', action='store_true', dest='ignore',
|
2012-10-02 05:46:12 +08:00
|
|
|
default=False, help='Ignores entries in the serialized data for fields'
|
|
|
|
' that do not 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
|
|
|
|
2012-11-10 09:17:43 +08:00
|
|
|
self.ignore = options.get('ignore')
|
|
|
|
self.using = options.get('database')
|
2014-02-09 20:22:29 +08:00
|
|
|
self.app_label = options.get('app_label')
|
|
|
|
self.hide_empty = options.get('hide_empty', False)
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2011-10-29 22:47:45 +08:00
|
|
|
if not len(fixture_labels):
|
2012-06-07 16:31:08 +08:00
|
|
|
raise CommandError(
|
2013-10-20 07:33:10 +08:00
|
|
|
"No database fixture specified. Please provide the path "
|
|
|
|
"of at least one fixture in the command line.")
|
2011-10-29 22:47:45 +08:00
|
|
|
|
2012-11-10 09:17:43 +08:00
|
|
|
self.verbosity = int(options.get('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()
|
|
|
|
self.compression_formats = {
|
2013-11-03 03:37:48 +08:00
|
|
|
None: open,
|
|
|
|
'gz': gzip.GzipFile,
|
|
|
|
'zip': SingleZipReader
|
2008-11-25 04:42:09 +08:00
|
|
|
}
|
2008-12-01 10:20:59 +08:00
|
|
|
if has_bz2:
|
2013-06-02 16:40:54 +08:00
|
|
|
self.compression_formats['bz2'] = bz2.BZ2File
|
2008-11-25 04:42:09 +08:00
|
|
|
|
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:
|
2014-02-09 20:22:29 +08:00
|
|
|
if self.fixture_count == 0 and self.hide_empty:
|
|
|
|
pass
|
|
|
|
elif self.fixture_object_count == self.loaded_object_count:
|
2013-06-02 16:40:54 +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:
|
2013-06-02 16:40:54 +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))
|
|
|
|
|
|
|
|
def load_label(self, fixture_label):
|
|
|
|
"""
|
|
|
|
Loads fixtures files for a given 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 = self.compression_formats[cmp_fmt]
|
2014-04-18 23:51:13 +08:00
|
|
|
# Forcing binary mode may be revisited after dropping Python 2 support (see #22399)
|
|
|
|
fixture = open_method(fixture_file, 'rb')
|
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:
|
|
|
|
self.stdout.write("Installing %s fixture '%s' from %s." %
|
|
|
|
(ser_fmt, fixture_name, humanize(fixture_dir)))
|
|
|
|
|
|
|
|
objects = serializers.deserialize(ser_fmt, fixture,
|
|
|
|
using=self.using, ignorenonexistent=self.ignore)
|
|
|
|
|
|
|
|
for obj in objects:
|
|
|
|
objects_in_fixture += 1
|
2013-07-30 19:08:59 +08:00
|
|
|
if router.allow_migrate(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)
|
|
|
|
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
|
|
|
|
|
|
|
|
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
|
2013-12-06 05:55:33 +08:00
|
|
|
if os.path.sep in fixture_name:
|
|
|
|
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
|
|
|
|
2013-06-02 16:40:54 +08:00
|
|
|
suffixes = ('.'.join(ext for ext in combo if ext)
|
|
|
|
for combo in product(databases, ser_fmts, cmp_fmts))
|
|
|
|
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 = []
|
|
|
|
for candidate in glob.iglob(os.path.join(fixture_dir, fixture_name + '*')):
|
|
|
|
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)
|
|
|
|
|
|
|
|
if fixture_name != 'initial_data' and not fixture_files:
|
|
|
|
# Warning kept for backwards-compatibility; why not an exception?
|
|
|
|
warnings.warn("No fixture named '%s' found." % fixture_name)
|
|
|
|
|
|
|
|
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 = []
|
2013-12-24 19:25:17 +08:00
|
|
|
for app_config in apps.get_app_configs():
|
2014-02-09 20:22:29 +08:00
|
|
|
if self.app_label and app_config.label != self.app_label:
|
|
|
|
continue
|
2013-12-14 02:28:42 +08:00
|
|
|
d = os.path.join(app_config.path, 'fixtures')
|
2013-06-02 16:40:54 +08:00
|
|
|
if os.path.isdir(d):
|
|
|
|
dirs.append(d)
|
|
|
|
dirs.extend(list(settings.FIXTURE_DIRS))
|
|
|
|
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'
|