Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

loaddata.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import functools
  2. import glob
  3. import gzip
  4. import os
  5. import sys
  6. import warnings
  7. import zipfile
  8. from itertools import product
  9. from django.apps import apps
  10. from django.conf import settings
  11. from django.core import serializers
  12. from django.core.exceptions import ImproperlyConfigured
  13. from django.core.management.base import BaseCommand, CommandError
  14. from django.core.management.color import no_style
  15. from django.core.management.utils import parse_apps_and_model_labels
  16. from django.db import (
  17. DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connections, router,
  18. transaction,
  19. )
  20. from django.utils.functional import cached_property
  21. try:
  22. import bz2
  23. has_bz2 = True
  24. except ImportError:
  25. has_bz2 = False
  26. READ_STDIN = '-'
  27. class Command(BaseCommand):
  28. help = 'Installs the named fixture(s) in the database.'
  29. missing_args_message = (
  30. "No database fixture specified. Please provide the path of at least "
  31. "one fixture in the command line."
  32. )
  33. def add_arguments(self, parser):
  34. parser.add_argument('args', metavar='fixture', nargs='+', help='Fixture labels.')
  35. parser.add_argument(
  36. '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS,
  37. help='Nominates a specific database to load fixtures into. Defaults to the "default" database.',
  38. )
  39. parser.add_argument(
  40. '--app', action='store', dest='app_label', default=None,
  41. help='Only look for fixtures in the specified app.',
  42. )
  43. parser.add_argument(
  44. '--ignorenonexistent', '-i', action='store_true', dest='ignore',
  45. help='Ignores entries in the serialized data for fields that do not '
  46. 'currently exist on the model.',
  47. )
  48. parser.add_argument(
  49. '-e', '--exclude', dest='exclude', action='append', default=[],
  50. help='An app_label or app_label.ModelName to exclude. Can be used multiple times.',
  51. )
  52. parser.add_argument(
  53. '--format', action='store', dest='format', default=None,
  54. help='Format of serialized data when reading from stdin.',
  55. )
  56. def handle(self, *fixture_labels, **options):
  57. self.ignore = options['ignore']
  58. self.using = options['database']
  59. self.app_label = options['app_label']
  60. self.verbosity = options['verbosity']
  61. self.excluded_models, self.excluded_apps = parse_apps_and_model_labels(options['exclude'])
  62. self.format = options['format']
  63. with transaction.atomic(using=self.using):
  64. self.loaddata(fixture_labels)
  65. # Close the DB connection -- unless we're still in a transaction. This
  66. # is required as a workaround for an edge case in MySQL: if the same
  67. # connection is used to create tables, load data, and query, the query
  68. # can return incorrect results. See Django #7572, MySQL #37735.
  69. if transaction.get_autocommit(self.using):
  70. connections[self.using].close()
  71. def loaddata(self, fixture_labels):
  72. connection = connections[self.using]
  73. # Keep a count of the installed objects and fixtures
  74. self.fixture_count = 0
  75. self.loaded_object_count = 0
  76. self.fixture_object_count = 0
  77. self.models = set()
  78. self.serialization_formats = serializers.get_public_serializer_formats()
  79. # Forcing binary mode may be revisited after dropping Python 2 support (see #22399)
  80. self.compression_formats = {
  81. None: (open, 'rb'),
  82. 'gz': (gzip.GzipFile, 'rb'),
  83. 'zip': (SingleZipReader, 'r'),
  84. 'stdin': (lambda *args: sys.stdin, None),
  85. }
  86. if has_bz2:
  87. self.compression_formats['bz2'] = (bz2.BZ2File, 'r')
  88. # Django's test suite repeatedly tries to load initial_data fixtures
  89. # from apps that don't have any fixtures. Because disabling constraint
  90. # checks can be expensive on some database (especially MSSQL), bail
  91. # out early if no fixtures are found.
  92. for fixture_label in fixture_labels:
  93. if self.find_fixtures(fixture_label):
  94. break
  95. else:
  96. return
  97. with connection.constraint_checks_disabled():
  98. for fixture_label in fixture_labels:
  99. self.load_label(fixture_label)
  100. # Since we disabled constraint checks, we must manually check for
  101. # any invalid keys that might have been added
  102. table_names = [model._meta.db_table for model in self.models]
  103. try:
  104. connection.check_constraints(table_names=table_names)
  105. except Exception as e:
  106. e.args = ("Problem installing fixtures: %s" % e,)
  107. raise
  108. # If we found even one object in a fixture, we need to reset the
  109. # database sequences.
  110. if self.loaded_object_count > 0:
  111. sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models)
  112. if sequence_sql:
  113. if self.verbosity >= 2:
  114. self.stdout.write("Resetting sequences\n")
  115. with connection.cursor() as cursor:
  116. for line in sequence_sql:
  117. cursor.execute(line)
  118. if self.verbosity >= 1:
  119. if self.fixture_object_count == self.loaded_object_count:
  120. self.stdout.write(
  121. "Installed %d object(s) from %d fixture(s)"
  122. % (self.loaded_object_count, self.fixture_count)
  123. )
  124. else:
  125. self.stdout.write(
  126. "Installed %d object(s) (of %d) from %d fixture(s)"
  127. % (self.loaded_object_count, self.fixture_object_count, self.fixture_count)
  128. )
  129. def load_label(self, fixture_label):
  130. """Load fixtures files for a given label."""
  131. show_progress = self.verbosity >= 3
  132. for fixture_file, fixture_dir, fixture_name in self.find_fixtures(fixture_label):
  133. _, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file))
  134. open_method, mode = self.compression_formats[cmp_fmt]
  135. fixture = open_method(fixture_file, mode)
  136. try:
  137. self.fixture_count += 1
  138. objects_in_fixture = 0
  139. loaded_objects_in_fixture = 0
  140. if self.verbosity >= 2:
  141. self.stdout.write(
  142. "Installing %s fixture '%s' from %s."
  143. % (ser_fmt, fixture_name, humanize(fixture_dir))
  144. )
  145. objects = serializers.deserialize(
  146. ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore,
  147. )
  148. for obj in objects:
  149. objects_in_fixture += 1
  150. if (obj.object._meta.app_config in self.excluded_apps or
  151. type(obj.object) in self.excluded_models):
  152. continue
  153. if router.allow_migrate_model(self.using, obj.object.__class__):
  154. loaded_objects_in_fixture += 1
  155. self.models.add(obj.object.__class__)
  156. try:
  157. obj.save(using=self.using)
  158. if show_progress:
  159. self.stdout.write(
  160. '\rProcessed %i object(s).' % loaded_objects_in_fixture,
  161. ending=''
  162. )
  163. # psycopg2 raises ValueError if data contains NUL chars.
  164. except (DatabaseError, IntegrityError, ValueError) as e:
  165. e.args = ("Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
  166. 'app_label': obj.object._meta.app_label,
  167. 'object_name': obj.object._meta.object_name,
  168. 'pk': obj.object.pk,
  169. 'error_msg': e,
  170. },)
  171. raise
  172. if objects and show_progress:
  173. self.stdout.write('') # add a newline after progress indicator
  174. self.loaded_object_count += loaded_objects_in_fixture
  175. self.fixture_object_count += objects_in_fixture
  176. except Exception as e:
  177. if not isinstance(e, CommandError):
  178. e.args = ("Problem installing fixture '%s': %s" % (fixture_file, e),)
  179. raise
  180. finally:
  181. fixture.close()
  182. # Warn if the fixture we loaded contains 0 objects.
  183. if objects_in_fixture == 0:
  184. warnings.warn(
  185. "No fixture data found for '%s'. (File format may be "
  186. "invalid.)" % fixture_name,
  187. RuntimeWarning
  188. )
  189. @functools.lru_cache(maxsize=None)
  190. def find_fixtures(self, fixture_label):
  191. """Find fixture files for a given label."""
  192. if fixture_label == READ_STDIN:
  193. return [(READ_STDIN, None, READ_STDIN)]
  194. fixture_name, ser_fmt, cmp_fmt = self.parse_name(fixture_label)
  195. databases = [self.using, None]
  196. cmp_fmts = list(self.compression_formats) if cmp_fmt is None else [cmp_fmt]
  197. ser_fmts = serializers.get_public_serializer_formats() if ser_fmt is None else [ser_fmt]
  198. if self.verbosity >= 2:
  199. self.stdout.write("Loading '%s' fixtures..." % fixture_name)
  200. if os.path.isabs(fixture_name):
  201. fixture_dirs = [os.path.dirname(fixture_name)]
  202. fixture_name = os.path.basename(fixture_name)
  203. else:
  204. fixture_dirs = self.fixture_dirs
  205. if os.path.sep in os.path.normpath(fixture_name):
  206. fixture_dirs = [os.path.join(dir_, os.path.dirname(fixture_name))
  207. for dir_ in fixture_dirs]
  208. fixture_name = os.path.basename(fixture_name)
  209. suffixes = (
  210. '.'.join(ext for ext in combo if ext)
  211. for combo in product(databases, ser_fmts, cmp_fmts)
  212. )
  213. targets = {'.'.join((fixture_name, suffix)) for suffix in suffixes}
  214. fixture_files = []
  215. for fixture_dir in fixture_dirs:
  216. if self.verbosity >= 2:
  217. self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir))
  218. fixture_files_in_dir = []
  219. path = os.path.join(fixture_dir, fixture_name)
  220. for candidate in glob.iglob(glob.escape(path) + '*'):
  221. if os.path.basename(candidate) in targets:
  222. # Save the fixture_dir and fixture_name for future error messages.
  223. fixture_files_in_dir.append((candidate, fixture_dir, fixture_name))
  224. if self.verbosity >= 2 and not fixture_files_in_dir:
  225. self.stdout.write("No fixture '%s' in %s." %
  226. (fixture_name, humanize(fixture_dir)))
  227. # Check kept for backwards-compatibility; it isn't clear why
  228. # duplicates are only allowed in different directories.
  229. if len(fixture_files_in_dir) > 1:
  230. raise CommandError(
  231. "Multiple fixtures named '%s' in %s. Aborting." %
  232. (fixture_name, humanize(fixture_dir)))
  233. fixture_files.extend(fixture_files_in_dir)
  234. if not fixture_files:
  235. raise CommandError("No fixture named '%s' found." % fixture_name)
  236. return fixture_files
  237. @cached_property
  238. def fixture_dirs(self):
  239. """
  240. Return a list of fixture directories.
  241. The list contains the 'fixtures' subdirectory of each installed
  242. application, if it exists, the directories in FIXTURE_DIRS, and the
  243. current directory.
  244. """
  245. dirs = []
  246. fixture_dirs = settings.FIXTURE_DIRS
  247. if len(fixture_dirs) != len(set(fixture_dirs)):
  248. raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.")
  249. for app_config in apps.get_app_configs():
  250. app_label = app_config.label
  251. app_dir = os.path.join(app_config.path, 'fixtures')
  252. if app_dir in fixture_dirs:
  253. raise ImproperlyConfigured(
  254. "'%s' is a default fixture directory for the '%s' app "
  255. "and cannot be listed in settings.FIXTURE_DIRS." % (app_dir, app_label)
  256. )
  257. if self.app_label and app_label != self.app_label:
  258. continue
  259. if os.path.isdir(app_dir):
  260. dirs.append(app_dir)
  261. dirs.extend(list(fixture_dirs))
  262. dirs.append('')
  263. dirs = [os.path.abspath(os.path.realpath(d)) for d in dirs]
  264. return dirs
  265. def parse_name(self, fixture_name):
  266. """
  267. Split fixture name in name, serialization format, compression format.
  268. """
  269. if fixture_name == READ_STDIN:
  270. if not self.format:
  271. raise CommandError('--format must be specified when reading from stdin.')
  272. return READ_STDIN, self.format, 'stdin'
  273. parts = fixture_name.rsplit('.', 2)
  274. if len(parts) > 1 and parts[-1] in self.compression_formats:
  275. cmp_fmt = parts[-1]
  276. parts = parts[:-1]
  277. else:
  278. cmp_fmt = None
  279. if len(parts) > 1:
  280. if parts[-1] in self.serialization_formats:
  281. ser_fmt = parts[-1]
  282. parts = parts[:-1]
  283. else:
  284. raise CommandError(
  285. "Problem installing fixture '%s': %s is not a known "
  286. "serialization format." % (''.join(parts[:-1]), parts[-1]))
  287. else:
  288. ser_fmt = None
  289. name = '.'.join(parts)
  290. return name, ser_fmt, cmp_fmt
  291. class SingleZipReader(zipfile.ZipFile):
  292. def __init__(self, *args, **kwargs):
  293. super().__init__(*args, **kwargs)
  294. if len(self.namelist()) != 1:
  295. raise ValueError("Zip-compressed fixtures must contain one file.")
  296. def read(self):
  297. return zipfile.ZipFile.read(self, self.namelist()[0])
  298. def humanize(dirname):
  299. return "'%s'" % dirname if dirname else 'absolute path'