Example #1
0
    def find_fixtures(self, fixture_label, fixture_dirs):
        """
        Search for fixture_label in fixture_dirs. Returns list of tuples.
        In each tuple first element is fixture's full path, second element
        is compression format.
        """
        fixtures = []
        for fixture_dir in fixture_dirs:
            if self.verbosity >= 2:
                self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

            label_found = False
            for combo in product(["json"], self.compression_formats):
                format, compression_format = combo
                file_name = ".".join(p for p in [self.fixture_name, format, compression_format] if p)

                if self.verbosity >= 3:
                    self.stdout.write(
                        "Trying %s for %s fixture '%s'...\n" % (humanize(fixture_dir), file_name, self.fixture_name)
                    )
                full_path = os.path.join(fixture_dir, file_name)
                try:
                    fixture = open_fixture(full_path, compression_format)
                except IOError:
                    if self.verbosity >= 2:
                        self.stdout.write(
                            "No %s fixture '%s' in %s.\n" % (format, self.fixture_name, humanize(fixture_dir))
                        )
                else:
                    try:
                        if label_found:
                            self.stderr.write(
                                "Multiple fixtures named '%s' in %s. Aborting.\n"
                                % (self.fixture_name, humanize(fixture_dir))
                            )
                            return

                        fixtures.append((full_path, compression_format))

                        if self.verbosity >= 2:
                            self.stdout.write(
                                "Installing %s fixture '%s' from %s.\n"
                                % (format, self.fixture_name, humanize(fixture_dir))
                            )

                        label_found = True
                    finally:
                        fixture.close()

        return fixtures
Example #2
0
    def find_fixtures(self, fixture_label, fixture_dirs):
        """
        Search for fixture_label in fixture_dirs. Returns list of tuples.
        In each tuple first element is fixture's full path, second element
        is compression format.
        """
        fixtures = []
        for fixture_dir in fixture_dirs:
            if self.verbosity >= 2:
                self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

            label_found = False
            for combo in product(['json'], self.compression_formats):
                format, compression_format = combo
                file_name = '.'.join(
                    p for p in [
                        self.fixture_name, format, compression_format
                    ]
                    if p
                )

                if self.verbosity >= 3:
                    self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                        (humanize(fixture_dir), file_name, self.fixture_name))
                full_path = os.path.join(fixture_dir, file_name)
                try:
                    fixture = open_fixture(full_path, compression_format)
                except IOError:
                    if self.verbosity >= 2:
                        self.stdout.write("No %s fixture '%s' in %s.\n" % \
                            (format, self.fixture_name, humanize(fixture_dir)))
                else:
                    try:
                        if label_found:
                            self.stderr.write("Multiple fixtures named '%s' in %s. Aborting.\n" %
                                (self.fixture_name, humanize(fixture_dir)))
                            return

                        fixtures.append((full_path, compression_format))

                        if self.verbosity >= 2:
                            self.stdout.write("Installing %s fixture '%s' from %s.\n" % \
                                (format, self.fixture_name, humanize(fixture_dir)))


                        label_found = True
                    finally:
                        fixture.close()

        return fixtures
Example #3
0
    def handle(self, *fixture_labels, **options):
        using = options.get('database', DEFAULT_DB_ALIAS)

        connection = connections[using]
        self.style = no_style()

        verbosity = int(options.get('verbosity', 1))
        show_traceback = options.get('traceback', False)

        # commit is a stealth option - it isn't really useful as
        # a command line option, but it can be useful when invoking
        # loaddata from within another script.
        # If commit=True, loaddata will use its own transaction;
        # if commit=False, the data load SQL will become part of
        # the transaction in place when loaddata was invoked.
        commit = options.get('commit', True)

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path'

        # Get a cursor (even though we don't need one yet). This has
        # the side effect of initializing the test database (if
        # it isn't already initialized).
        cursor = connection.cursor()

        # Start transaction management. All fixtures are installed in a
        # single transaction to ensure that all references are resolved.
        if commit:
            transaction.commit_unless_managed(using=using)
            transaction.enter_transaction_management(using=using)
            transaction.managed(True, using=using)

        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(
                        self.namelist()
                    ) == 1, "Zip-compressed fixtures must contain only one file."

            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None: file,
            'gz': gzip.GzipFile,
            'zip': SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [
            os.path.join(os.path.dirname(path), 'fixtures')
            for path in app_module_paths
        ]
        for fixture_label in fixture_labels:
            parts = fixture_label.split('.')

            if len(parts) > 1 and parts[-1] in compression_types:
                compression_formats = [parts[-1]]
                parts = parts[:-1]
            else:
                compression_formats = compression_types.keys()

            if len(parts) == 1:
                fixture_name = parts[0]
                formats = serializers.get_public_serializer_formats()
            else:
                fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                if format in serializers.get_public_serializer_formats():
                    formats = [format]
                else:
                    formats = []

            if formats:
                if verbosity > 1:
                    self.stdout.write("Loading '%s' fixtures...\n" %
                                      fixture_name)
            else:
                self.stderr.write(
                    self.style.ERROR(
                        "Problem installing fixture '%s': %s is not a known serialization format.\n"
                        % (fixture_name, format)))
                if commit:
                    transaction.rollback(using=using)
                    transaction.leave_transaction_management(using=using)
                return

            if os.path.isabs(fixture_name):
                fixture_dirs = [fixture_name]
            else:
                fixture_dirs = app_fixtures + list(
                    settings.FIXTURE_DIRS) + ['']

            for fixture_dir in fixture_dirs:
                if verbosity > 1:
                    self.stdout.write("Checking %s for fixtures...\n" %
                                      humanize(fixture_dir))

                label_found = False
                for combo in product([using, None], formats,
                                     compression_formats):
                    database, format, compression_format = combo
                    file_name = '.'.join(
                        p for p in
                        [fixture_name, database, format, compression_format]
                        if p)

                    if verbosity > 1:
                        self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                            (humanize(fixture_dir), file_name, fixture_name))
                    full_path = os.path.join(fixture_dir, file_name)
                    open_method = compression_types[compression_format]
                    try:
                        fixture = open_method(full_path, 'r')
                        if label_found:
                            fixture.close()
                            self.stderr.write(
                                self.style.ERROR(
                                    "Multiple fixtures named '%s' in %s. Aborting.\n"
                                    % (fixture_name, humanize(fixture_dir))))
                            if commit:
                                transaction.rollback(using=using)
                                transaction.leave_transaction_management(
                                    using=using)
                            return
                        else:
                            fixture_count += 1
                            objects_in_fixture = 0
                            loaded_objects_in_fixture = 0
                            if verbosity > 0:
                                self.stdout.write("Installing %s fixture '%s' from %s.\n" % \
                                    (format, fixture_name, humanize(fixture_dir)))
                            try:
                                objects = serializers.deserialize(format,
                                                                  fixture,
                                                                  using=using)
                                for obj in objects:
                                    objects_in_fixture += 1
                                    if router.allow_syncdb(
                                            using, obj.object.__class__):
                                        loaded_objects_in_fixture += 1
                                        models.add(obj.object.__class__)
                                        obj.save(using=using)
                                loaded_object_count += loaded_objects_in_fixture
                                fixture_object_count += objects_in_fixture
                                label_found = True
                            except (SystemExit, KeyboardInterrupt):
                                raise
                            except Exception:
                                import traceback
                                fixture.close()
                                if commit:
                                    transaction.rollback(using=using)
                                    transaction.leave_transaction_management(
                                        using=using)
                                if show_traceback:
                                    traceback.print_exc()
                                else:
                                    self.stderr.write(
                                        self.style.ERROR(
                                            "Problem installing fixture '%s': %s\n"
                                            % (full_path, ''.join(
                                                traceback.format_exception(
                                                    sys.exc_type,
                                                    sys.exc_value,
                                                    sys.exc_traceback)))))
                                return
                            fixture.close()

                            # If the fixture we loaded contains 0 objects, assume that an
                            # error was encountered during fixture loading.
                            if objects_in_fixture == 0:
                                self.stderr.write(
                                    self.style.ERROR(
                                        "No fixture data found for '%s'. (File format may be invalid.)\n"
                                        % (fixture_name)))
                                if commit:
                                    transaction.rollback(using=using)
                                    transaction.leave_transaction_management(
                                        using=using)
                                return

                    except Exception, e:
                        if verbosity > 1:
                            self.stdout.write("No %s fixture '%s' in %s.\n" % \
                                (format, fixture_name, humanize(fixture_dir)))
Example #4
0
    def handle(self, *fixture_labels, **options):
        using = options.get('database')

        connection = connections[using]
        self.style = no_style()

        verbosity = int(options.get('verbosity'))
        show_traceback = options.get('traceback')

        # commit is a stealth option - it isn't really useful as
        # a command line option, but it can be useful when invoking
        # loaddata from within another script.
        # If commit=True, loaddata will use its own transaction;
        # if commit=False, the data load SQL will become part of
        # the transaction in place when loaddata was invoked.
        commit = options.get('commit', True)

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path'

        # Get a cursor (even though we don't need one yet). This has
        # the side effect of initializing the test database (if
        # it isn't already initialized).
        cursor = connection.cursor()

        # Start transaction management. All fixtures are installed in a
        # single transaction to ensure that all references are resolved.
        if commit:
            transaction.commit_unless_managed(using=using)
            transaction.enter_transaction_management(using=using)
            transaction.managed(True, using=using)

        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None:   open,
            'gz':   gzip.GzipFile,
            'zip':  SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]
        for fixture_label in fixture_labels:
            parts = fixture_label.split('.')

            if len(parts) > 1 and parts[-1] in compression_types:
                compression_formats = [parts[-1]]
                parts = parts[:-1]
            else:
                compression_formats = compression_types.keys()

            if len(parts) == 1:
                fixture_name = parts[0]
                formats = serializers.get_public_serializer_formats()
            else:
                fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                if format in serializers.get_public_serializer_formats():
                    formats = [format]
                else:
                    formats = []

            if formats:
                if verbosity >= 2:
                    self.stdout.write("Loading '%s' fixtures...\n" % fixture_name)
            else:
                self.stderr.write(
                    self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" %
                        (fixture_name, format)))
                if commit:
                    transaction.rollback(using=using)
                    transaction.leave_transaction_management(using=using)
                return

            if os.path.isabs(fixture_name):
                fixture_dirs = [fixture_name]
            else:
                fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']

            for fixture_dir in fixture_dirs:
                if verbosity >= 2:
                    self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

                label_found = False
                for combo in product([using, None], formats, compression_formats):
                    database, format, compression_format = combo
                    file_name = '.'.join(
                        p for p in [
                            fixture_name, database, format, compression_format
                        ]
                        if p
                    )

                    if verbosity >= 3:
                        self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                            (humanize(fixture_dir), file_name, fixture_name))
                    full_path = os.path.join(fixture_dir, file_name)
                    open_method = compression_types[compression_format]
                    try:
                        fixture = open_method(full_path, 'r')
                        if label_found:
                            fixture.close()
                            self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" %
                                (fixture_name, humanize(fixture_dir))))
                            if commit:
                                transaction.rollback(using=using)
                                transaction.leave_transaction_management(using=using)
                            return
                        else:
                            fixture_count += 1
                            objects_in_fixture = 0
                            loaded_objects_in_fixture = 0
                            if verbosity >= 2:
                                self.stdout.write("Installing %s fixture '%s' from %s.\n" % \
                                    (format, fixture_name, humanize(fixture_dir)))
                            try:
                                objects = serializers.deserialize(format, fixture, using=using)

                                with connection.constraint_checks_disabled():
                                    for obj in objects:
                                        objects_in_fixture += 1
                                        if router.allow_syncdb(using, obj.object.__class__):
                                            loaded_objects_in_fixture += 1
                                            models.add(obj.object.__class__)
                                            try:
                                                obj.save(using=using)
                                            except (DatabaseError, IntegrityError), e:
                                                msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
                                                        'app_label': obj.object._meta.app_label,
                                                        'object_name': obj.object._meta.object_name,
                                                        'pk': obj.object.pk,
                                                        'error_msg': e
                                                    }
                                                raise e.__class__, e.__class__(msg), sys.exc_info()[2]

                                # 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 models]
                                connection.check_constraints(table_names=table_names)

                                loaded_object_count += loaded_objects_in_fixture
                                fixture_object_count += objects_in_fixture
                                label_found = True
                            except (SystemExit, KeyboardInterrupt):
                                raise
                            except Exception:
                                import traceback
                                fixture.close()
                                if commit:
                                    transaction.rollback(using=using)
                                    transaction.leave_transaction_management(using=using)
                                if show_traceback:
                                    traceback.print_exc()
                                else:
                                    self.stderr.write(
                                        self.style.ERROR("Problem installing fixture '%s': %s\n" %
                                             (full_path, ''.join(traceback.format_exception(sys.exc_type,
                                                 sys.exc_value, sys.exc_traceback)))))
                                return
                            fixture.close()

                            # If the fixture we loaded contains 0 objects, assume that an
                            # error was encountered during fixture loading.
                            if objects_in_fixture == 0:
                                self.stderr.write(
                                    self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)\n" %
                                        (fixture_name)))
                                if commit:
                                    transaction.rollback(using=using)
                                    transaction.leave_transaction_management(using=using)
                                return

                    except Exception, e:
                        if verbosity >= 2:
                            self.stdout.write("No %s fixture '%s' in %s.\n" % \
                                (format, fixture_name, humanize(fixture_dir)))
Example #5
0
    def load_fixture(self, fixture_label, using, commit=True):
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        parts = fixture_label.split('.')

        if len(parts) > 1 and parts[-1] in compression_types:
            compression_formats = [parts[-1]]
            parts = parts[:-1]
        else:
            compression_formats = compression_types.keys()

        if len(parts) == 1:
            fixture_name = parts[0]
            formats = serializers.get_public_serializer_formats()
        else:
            fixture_name, format = '.'.join(parts[:-1]), parts[-1]
            if format in serializers.get_public_serializer_formats():
                formats = [format]
            else:
                formats = []

        if formats:
            if self.verbosity >= 2:
                self.stdout.write("Loading '%s' fixtures...\n" % fixture_name)
        else:
            self.stderr.write(
                self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" %
                    (fixture_name, format)))
            if commit:
                transaction.rollback(using=using)
                transaction.leave_transaction_management(using=using)
            return

        if os.path.isabs(fixture_name):
            fixture_dirs = [fixture_name]
        else:
            fixture_dirs = self.get_app_fixtures() + list(settings.FIXTURE_DIRS) + ['']

        for fixture_dir in fixture_dirs:
            if self.verbosity >= 2:
                self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

            label_found = False
            for combo in product([using, None], formats, compression_formats):
                database, format, compression_format = combo
                file_name = '.'.join(
                    p for p in [
                        fixture_name, database, format, compression_format
                    ]
                    if p
                )

                if self.verbosity >= 3:
                    self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                        (humanize(fixture_dir), file_name, fixture_name))
                full_path = os.path.join(fixture_dir, file_name)
                open_method = compression_types[compression_format]
                try:
                    fixture = open_method(full_path, 'r')
                except IOError:
                    if self.verbosity >= 2:
                        self.stdout.write("No %s fixture '%s' in %s.\n" % \
                            (format, fixture_name, humanize(fixture_dir)))
                    continue
                try:
                    if label_found:
                        self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" %
                            (fixture_name, humanize(fixture_dir))))
                        if commit:
                            transaction.rollback(using=using)
                            transaction.leave_transaction_management(using=using)
                        return

                    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.\n" % \
                            (format, fixture_name, humanize(fixture_dir)))

                    objects = serializers.deserialize(format, fixture, using=using)

                    for obj in objects:
                        objects_in_fixture += 1
                        if router.allow_syncdb(using, obj.object.__class__):
                            loaded_objects_in_fixture += 1
                            models.add(obj.object.__class__)
                            try:
                                obj.save(using=using)
                            except (DatabaseError, IntegrityError), e:
                                msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
                                        'app_label': obj.object._meta.app_label,
                                        'object_name': obj.object._meta.object_name,
                                        'pk': obj.object.pk,
                                        'error_msg': e
                                    }
                                raise e.__class__, e.__class__(msg), sys.exc_info()[2]

                    loaded_object_count += loaded_objects_in_fixture
                    fixture_object_count += objects_in_fixture
                    label_found = True

                except (SystemExit, KeyboardInterrupt):
                    raise
                except Exception:
                    if self.show_traceback:
                        traceback.print_exc()
                    else:
                        self.stderr.write(
                            self.style.ERROR("Problem installing fixture '%s': %s\n" %
                                 (full_path, ''.join(traceback.format_exception(sys.exc_type,
                                     sys.exc_value, sys.exc_traceback)))))
Example #6
0
def tables_used_by_fixtures(fixture_labels, using=DEFAULT_DB_ALIAS):
    """Act like Django's stock loaddata command, but, instead of loading data,
    return an iterable of the names of the tables into which data would be
    loaded."""
    # Keep a count of the installed objects and fixtures
    fixture_count = 0
    loaded_object_count = 0
    fixture_object_count = 0
    tables = set()

    class SingleZipReader(zipfile.ZipFile):
        def __init__(self, *args, **kwargs):
            zipfile.ZipFile.__init__(self, *args, **kwargs)
            if settings.DEBUG:
                assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
        def read(self):
            return zipfile.ZipFile.read(self, self.namelist()[0])

    compression_types = {
        None:   file,
        'gz':   gzip.GzipFile,
        'zip':  SingleZipReader
    }
    if has_bz2:
        compression_types['bz2'] = bz2.BZ2File

    app_module_paths = []
    for app in get_apps():
        if hasattr(app, '__path__'):
            # It's a 'models/' subpackage
            for path in app.__path__:
                app_module_paths.append(path)
        else:
            # It's a models.py module
            app_module_paths.append(app.__file__)

    app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]
    for fixture_label in fixture_labels:
        parts = fixture_label.split('.')

        if len(parts) > 1 and parts[-1] in compression_types:
            compression_formats = [parts[-1]]
            parts = parts[:-1]
        else:
            compression_formats = list(compression_types.keys())

        if len(parts) == 1:
            fixture_name = parts[0]
            formats = serializers.get_public_serializer_formats()
        else:
            fixture_name, format = '.'.join(parts[:-1]), parts[-1]
            if format in serializers.get_public_serializer_formats():
                formats = [format]
            else:
                formats = []

        if not formats:
            # stderr.write(style.ERROR("Problem installing fixture '%s': %s is
            # not a known serialization format.\n" % (fixture_name, format)))
            return set()

        if os.path.isabs(fixture_name):
            fixture_dirs = [fixture_name]
        else:
            fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']

        for fixture_dir in fixture_dirs:
            # stdout.write("Checking %s for fixtures...\n" %
            # humanize(fixture_dir))

            label_found = False
            for combo in product([using, None], formats, compression_formats):
                database, format, compression_format = combo
                file_name = '.'.join(
                    p for p in [
                        fixture_name, database, format, compression_format
                    ]
                    if p
                )

                # stdout.write("Trying %s for %s fixture '%s'...\n" % \
                # (humanize(fixture_dir), file_name, fixture_name))
                full_path = os.path.join(fixture_dir, file_name)
                open_method = compression_types[compression_format]
                try:
                    fixture = open_method(full_path, 'r')
                    if label_found:
                        fixture.close()
                        # stderr.write(style.ERROR("Multiple fixtures named
                        # '%s' in %s. Aborting.\n" % (fixture_name,
                        # humanize(fixture_dir))))
                        return set()
                    else:
                        fixture_count += 1
                        objects_in_fixture = 0
                        loaded_objects_in_fixture = 0
                        # stdout.write("Installing %s fixture '%s' from %s.\n"
                        # % (format, fixture_name, humanize(fixture_dir)))
                        try:
                            objects = serializers.deserialize(format, fixture, using=using)
                            for obj in objects:
                                objects_in_fixture += 1
                                if router.allow_syncdb(using, obj.object.__class__):
                                    loaded_objects_in_fixture += 1
                                    tables.add(
                                        obj.object.__class__._meta.db_table)
                            loaded_object_count += loaded_objects_in_fixture
                            fixture_object_count += objects_in_fixture
                            label_found = True
                        except (SystemExit, KeyboardInterrupt):
                            raise
                        except Exception:
                            fixture.close()
                            # stderr.write( style.ERROR("Problem installing
                            # fixture '%s': %s\n" % (full_path, ''.join(tra
                            # ceback.format_exception(sys.exc_type,
                            # sys.exc_value, sys.exc_traceback)))))
                            return set()
                        fixture.close()

                        # If the fixture we loaded contains 0 objects, assume that an
                        # error was encountered during fixture loading.
                        if objects_in_fixture == 0:
                            # stderr.write( style.ERROR("No fixture data found
                            # for '%s'. (File format may be invalid.)\n" %
                            # (fixture_name)))
                            return set()

                except Exception:
                    # stdout.write("No %s fixture '%s' in %s.\n" % \ (format,
                    # fixture_name, humanize(fixture_dir)))
                    pass

    return tables
Example #7
0
    def get_posting_list(cls, movie_id):
        try:
            return cls.objects.get(movie_id=movie_id).scores
        except MMovieVectorTable.DoesNotExist:
            return None



if __name__ == "__main__":
    list_of_mmovies = MMovieVector.objects.all()
    list_of_mmovie_vectors = []
    for mm in list_of_mmovies:
        list_of_mmovie_vectors.append(mm.to_movie_vector())
#    list_of_mmovie_vectors=list_of_mmovie_vectors[1:5]
    boosts = {'movie_name':0,'subcates':0.04, 'directors':0.36, 'casts':0.36,\
                     'location':0.07, 'release_date':0.01, 'imdb_score':0.01,\
                      'is_HD':0, 'is_free':0, 'is_single_movie':0,'view_count':0.4}
    #t1 = time.time()
    for m1 , m2 in product(list_of_mmovie_vectors, list_of_mmovie_vectors):
        t1 = time.time()
        if m2['movie_id'] > m1['movie_id']:
            score = MMovieVectorTable.calc_2movie_score(m1, m2, **boosts)
            if score > 0.25:
                MMovieVectorTable.add_or_update_movie_score(m1['movie_id'], m2['movie_id'], score)
            #print "[%d - % d] : %f" %(m1['movie_id'], m2['movie_id'], score)
        #print (time.time()-t1)*1000
    list_of_results = MMovieVectorTable.objects.all()
    for i in list_of_results:
        print i.movie_id,  len(i.scores)

    def handle(self, *fixture_labels, **options):
        using = options.get('database')

        connection = connections[using]
        self.style = no_style()

        if not len(fixture_labels):
            self.stderr.write(
                self.style.ERROR("No database fixture specified. Please provide the path of at least one fixture in the command line.\n")
            )
            return

        verbosity = int(options.get('verbosity'))
        show_traceback = options.get('traceback')

        # commit is a stealth option - it isn't really useful as
        # a command line option, but it can be useful when invoking
        # loaddata from within another script.
        # If commit=True, loaddata will use its own transaction;
        # if commit=False, the data load SQL will become part of
        # the transaction in place when loaddata was invoked.
        commit = options.get('commit', True)

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: "'%s'" % dirname if dirname else 'absolute path'

        # Get a cursor (even though we don't need one yet). This has
        # the side effect of initializing the test database (if
        # it isn't already initialized).
        cursor = connection.cursor()

        # Start transaction management. All fixtures are installed in a
        # single transaction to ensure that all references are resolved.
        if commit:
            transaction.commit_unless_managed(using=using)
            transaction.enter_transaction_management(using=using)
            transaction.managed(True, using=using)

        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None:   open,
            'gz':   gzip.GzipFile,
            'zip':  SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]

        try:
            with connection.constraint_checks_disabled():
                for fixture_label in fixture_labels:
                    parts = fixture_label.split('.')

                    if len(parts) > 1 and parts[-1] in compression_types:
                        compression_formats = [parts[-1]]
                        parts = parts[:-1]
                    else:
                        compression_formats = compression_types.keys()

                    if len(parts) == 1:
                        fixture_name = parts[0]
                        formats = serializers.get_public_serializer_formats()
                    else:
                        fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                        if format in serializers.get_public_serializer_formats():
                            formats = [format]
                        else:
                            formats = []

                    if formats:
                        if verbosity >= 2:
                            self.stdout.write("Loading '%s' fixtures...\n" % fixture_name)
                    else:
                        self.stderr.write(
                            self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" %
                                             (fixture_name, format)))
                        if commit:
                            transaction.rollback(using=using)
                            transaction.leave_transaction_management(using=using)
                        return

                    if os.path.isabs(fixture_name):
                        fixture_dirs = [fixture_name]
                    else:
                        fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']

                    for fixture_dir in fixture_dirs:
                        if verbosity >= 2:
                            self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

                        label_found = False
                        for combo in product([using, None], formats, compression_formats):
                            database, format, compression_format = combo
                            file_name = '.'.join(
                                p for p in [
                                    fixture_name, database, format, compression_format
                                ]
                                    if p
                            )

                            if verbosity >= 3:
                                self.stdout.write("Trying %s for %s fixture '%s'...\n" %\
                                                  (humanize(fixture_dir), file_name, fixture_name))
                            full_path = os.path.join(fixture_dir, file_name)
                            open_method = compression_types[compression_format]
                            try:
                                fixture = open_method(full_path, 'r')
                            except IOError:
                                if verbosity >= 2:
                                    self.stdout.write("No %s fixture '%s' in %s.\n" %\
                                                      (format, fixture_name, humanize(fixture_dir)))
                            else:
                                try:
                                    if label_found:
                                        self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" %
                                                                           (fixture_name, humanize(fixture_dir))))
                                        if commit:
                                            transaction.rollback(using=using)
                                            transaction.leave_transaction_management(using=using)
                                        return

                                    fixture_count += 1
                                    objects_in_fixture = 0
                                    loaded_objects_in_fixture = 0
                                    if verbosity >= 2:
                                        self.stdout.write("Installing %s fixture '%s' from %s.\n" %\
                                                          (format, fixture_name, humanize(fixture_dir)))

                                    objects = serializers.deserialize(format, fixture, using=using)

                                    object_write_buffer = {}
                                    for obj in objects:
                                        objects_in_fixture += 1
                                        if router.allow_syncdb(using, obj.object.__class__):
                                            loaded_objects_in_fixture += 1
                                            models.add(obj.object.__class__)
                                            try:
                                                obj.save(using=using)
                                                #todo The commented code below (and after the except) should activate an alternative save that is done in bulk. Not working yet...
#                                                the_model = type(obj.object)
#                                                if the_model not in object_write_buffer:
#                                                    object_write_buffer.update({the_model:[]})
#                                                item = {}
#                                                item.update( {'account':obj.object.account})
#                                                for field in obj.object._meta.fields:
#                                                    item.update( {field.attname : getattr(obj.object, field.attname ) } )
#                                                object_write_buffer[the_model].append(item)
#                                                if len(object_write_buffer[the_model]) > 500:
#                                                    the_model.objects.bulk_insert(object_write_buffer[the_model])
#                                                    object_write_buffer[the_model]=[]
                                            except (DatabaseError, IntegrityError), e:
                                                msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
                                                    'app_label': obj.object._meta.app_label,
                                                    'object_name': obj.object._meta.object_name,
                                                    'pk': obj.object.pk,
                                                    'error_msg': e
                                                }
                                                raise e.__class__, e.__class__(msg), sys.exc_info()[2]

#                                    for the_model in object_write_buffer.keys():
#                                        if len(object_write_buffer[the_model]) > 0:
#                                            the_model.objects.bulk_insert(object_write_buffer[the_model])
#                                            object_write_buffer[the_model]=[]


                                    loaded_object_count += loaded_objects_in_fixture
                                    fixture_object_count += objects_in_fixture
                                    label_found = True
                                finally:
                                    fixture.close()

                                # If the fixture we loaded contains 0 objects, assume that an
                                # error was encountered during fixture loading.
                                if objects_in_fixture == 0:
                                    self.stderr.write(
                                        self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)\n" %
                                                         (fixture_name)))
                                    if commit:
                                        transaction.rollback(using=using)
                                        transaction.leave_transaction_management(using=using)
                                    return


        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception:
            if commit:
                transaction.rollback(using=using)
                transaction.leave_transaction_management(using=using)
            if show_traceback:
                traceback.print_exc()
            else:
                self.stderr.write(
                    self.style.ERROR("Problem installing fixture '%s': %s\n" %
                                     (full_path, ''.join(traceback.format_exception(sys.exc_type,
                                         sys.exc_value, sys.exc_traceback)))))
            return


        # If we found even one object in a fixture, we need to reset the
        # database sequences.
        if loaded_object_count > 0:
            sequence_sql = connection.ops.sequence_reset_sql(self.style, models)
            if sequence_sql:
                if verbosity >= 2:
                    self.stdout.write("Resetting sequences\n")
                for line in sequence_sql:
                    cursor.execute(line)

        if commit:
            transaction.commit(using=using)
            transaction.leave_transaction_management(using=using)

        if verbosity >= 1:
            if fixture_object_count == loaded_object_count:
                self.stdout.write("Installed %d object(s) from %d fixture(s)\n" % (
                    loaded_object_count, fixture_count))
            else:
                self.stdout.write("Installed %d object(s) (of %d) from %d fixture(s)\n" % (
                    loaded_object_count, fixture_object_count, fixture_count))

        # Close the DB connection. 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 commit:
            connection.close()
Example #9
0
    def handle(self, *fixture_labels, **options):
        '''
            All database code is unnecessary but remove it will broke.
        '''

        #TODO remove database, connection code and stuff

        using = options.get('database')

        connection = connections[using]
        self.style = no_style()

        if not len(fixture_labels):
            print("No database fixture specified. Please provide the path of at least one fixture in the command line.\n")
            return

        verbosity = int(options.get('verbosity'))
        show_traceback = options.get('traceback')

        # commit is a stealth option - it isn't really useful as
        # a command line option, but it can be useful when invoking
        # loaddata from within another script.
        # If commit=True, loaddata will use its own transaction;
        # if commit=False, the data load SQL will become part of
        # the transaction in place when loaddata was invoked.
        commit = options.get('commit', True)

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: "'%s'" % dirname if dirname else 'absolute path'

        # Get a cursor (even though we don't need one yet). This has
        # the side effect of initializing the test database (if
        # it isn't already initialized).
        cursor = connection.cursor()

        # Start transaction management. All fixtures are installed in a
        # single transaction to ensure that all references are resolved.
        if commit:
            transaction.commit_unless_managed(using=using)
            transaction.enter_transaction_management(using=using)
            transaction.managed(True, using=using)

        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None:   open,
            'gz':   gzip.GzipFile,
            'zip':  SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]

        instances = []
        apps = set()

        try:
            #with connection.constraint_checks_disabled():
            for fixture_label in fixture_labels:
                parts = fixture_label.split('.')

                if len(parts) > 1 and parts[-1] in compression_types:
                    compression_formats = [parts[-1]]
                    parts = parts[:-1]
                else:
                    compression_formats = compression_types.keys()

                if len(parts) == 1:
                    fixture_name = parts[0]
                    formats = serializers.get_public_serializer_formats()
                else:
                    fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                    if format in serializers.get_public_serializer_formats():
                        formats = [format]
                    else:
                        formats = []

                if formats:
                    if verbosity >= 2:
                        print("Loading '%s' fixtures...\n" % fixture_name)
                else:
                    print("Problem installing fixture '%s': %s is not a known serialization format.\n" %
                            (fixture_name, format))
                    if commit:
                        transaction.rollback(using=using)
                        transaction.leave_transaction_management(using=using)
                    return

                if os.path.isabs(fixture_name):
                    fixture_dirs = [fixture_name]
                else:
                    fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']

                for fixture_dir in fixture_dirs:
                    if verbosity >= 2:
                        self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

                    label_found = False
                    for combo in product([using, None], formats, compression_formats):
                        database, format, compression_format = combo
                        file_name = '.'.join(
                            p for p in [
                                fixture_name, database, format, compression_format
                            ]
                            if p
                        )

                        if verbosity >= 3:
                            self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                                (humanize(fixture_dir), file_name, fixture_name))
                        full_path = os.path.join(fixture_dir, file_name)
                        open_method = compression_types[compression_format]
                        try:
                            fixture = open_method(full_path, 'r')
                        except IOError:
                            if verbosity >= 2:
                                self.stdout.write("No %s fixture '%s' in %s.\n" % \
                                    (format, fixture_name, humanize(fixture_dir)))
                        else:
                            try:
                                if label_found:
                                    print("Multiple fixtures named '%s' in %s. Aborting.\n" %
                                        (fixture_name, humanize(fixture_dir)))
                                    if commit:
                                        transaction.rollback(using=using)
                                        transaction.leave_transaction_management(using=using)
                                    return

                                fixture_count += 1
                                objects_in_fixture = 0
                                loaded_objects_in_fixture = 0
                                if verbosity >= 2:
                                    self.stdout.write("Installing %s fixture '%s' from %s.\n" % \
                                        (format, fixture_name, humanize(fixture_dir)))

                                objects = serializers.deserialize(format, fixture, using=using)

                                for obj in objects:
                                    objects_in_fixture += 1
                                    if router.allow_syncdb(using, obj.object.__class__):
                                        loaded_objects_in_fixture += 1
                                        models.add(obj.object.__class__)
                                        try:
                                            obj.object.save = partial(memory_save, obj.object)
                                            #if obj.object.__class__.__name__ == "PedidoExame":
                                            #    import ipdb; ipdb.set_trace() ### XXX BREAKPOINT
                                            obj.object.save()
                                            instances.append(obj)

                                        except (DatabaseError, IntegrityError), e:
                                            msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
                                                    'app_label': obj.object._meta.app_label,
                                                    'object_name': obj.object._meta.object_name,
                                                    'pk': obj.object.pk,
                                                    'error_msg': e
                                                }
                                            raise e.__class__, e.__class__(msg), sys.exc_info()[2]

                                loaded_object_count += loaded_objects_in_fixture
                                fixture_object_count += objects_in_fixture
                                label_found = True
                            finally:
                                fixture.close()

                            # If the fixture we loaded contains 0 objects, assume that an
                            # error was encountered during fixture loading.
                            if objects_in_fixture == 0:
                                print("No fixture data found for '%s'. (File format may be invalid.)\n" %
                                        (fixture_name))
                                if commit:
                                    transaction.rollback(using=using)
                                    transaction.leave_transaction_management(using=using)
                                return

            # 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 models]
Example #10
0
    def handle(self, *fixture_labels, **options):
        using = options.get('database', DEFAULT_DB_ALIAS)

        connection = connections[using]
        self.style = no_style()

        verbosity = int(options.get('verbosity', 1))
        show_traceback = options.get('traceback', False)

        # commit is a stealth option - it isn't really useful as
        # a command line option, but it can be useful when invoking
        # loaddata from within another script.
        # If commit=True, loaddata will use its own transaction;
        # if commit=False, the data load SQL will become part of
        # the transaction in place when loaddata was invoked.
        commit = options.get('commit', True)

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path'

        # Get a cursor (even though we don't need one yet). This has
        # the side effect of initializing the test database (if
        # it isn't already initialized).
        cursor = connection.cursor()

        # Start transaction management. All fixtures are installed in a
        # single transaction to ensure that all references are resolved.
        if commit:
            transaction.commit_unless_managed(using=using)
            transaction.enter_transaction_management(using=using)
            transaction.managed(True, using=using)

        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None:   file,
            'gz':   gzip.GzipFile,
            'zip':  SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        for fixture_label in fixture_labels:
            parts = fixture_label.split('.')

            if len(parts) > 1 and parts[-1] in compression_types:
                compression_formats = [parts[-1]]
                parts = parts[:-1]
            else:
                compression_formats = compression_types.keys()

            if len(parts) == 1:
                fixture_name = parts[0]
                formats = serializers.get_public_serializer_formats()
            else:
                fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                if format in serializers.get_public_serializer_formats():
                    formats = [format]
                else:
                    formats = []

            if formats:
                if verbosity >= 2:
                    self.stdout.write("Loading '%s' fixtures...\n" % fixture_name)
            else:
                self.stderr.write(
                    self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" %
                        (fixture_name, format)))
                if commit:
                    transaction.rollback(using=using)
                    transaction.leave_transaction_management(using=using)
                return

            if os.path.isabs(fixture_name):
                fixture_dirs = [fixture_name]
            else:
                fixture_dirs = self._get_app_fixtures() + list(settings.FIXTURE_DIRS) + ['']

            for fixture_dir in fixture_dirs:
                if verbosity >= 2:
                    self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

                label_found = False
                for combo in product([using, None], formats, compression_formats):
                    database, format, compression_format = combo
                    file_name = '.'.join(
                        p for p in [
                            fixture_name, database, format, compression_format
                        ]
                        if p
                    )

                    if verbosity >= 3:
                        self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                            (humanize(fixture_dir), file_name, fixture_name))
                    full_path = os.path.join(fixture_dir, file_name)
                    open_method = compression_types[compression_format]
                    try:
                        fixture = open_method(full_path, 'r')
                        if label_found:
                            fixture.close()
                            self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" %
                                (fixture_name, humanize(fixture_dir))))
                            if commit:
                                transaction.rollback(using=using)
                                transaction.leave_transaction_management(using=using)
                            return
                        else:
                            fixture_count += 1
                            objects_in_fixture = 0
                            loaded_objects_in_fixture = 0
                            if verbosity >= 2:
                                self.stdout.write("Installing %s fixture '%s' from %s.\n" % \
                                    (format, fixture_name, humanize(fixture_dir)))
                            try:
                                objects = serializers.deserialize(format, fixture, using=using)

                                with connection.constraint_checks_disabled():
                                    for obj in objects:
                                        objects_in_fixture += 1
                                        if router.allow_syncdb(using, obj.object.__class__):
                                            loaded_objects_in_fixture += 1
                                            models.add(obj.object.__class__)
                                            obj.save(using=using)

                                # 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 models]
                                connection.check_constraints(table_names=table_names)

                                loaded_object_count += loaded_objects_in_fixture
                                fixture_object_count += objects_in_fixture
                                label_found = True
                            except (SystemExit, KeyboardInterrupt):
                                raise
                            except Exception:
                                import traceback
                                fixture.close()
                                if commit:
                                    transaction.rollback(using=using)
                                    transaction.leave_transaction_management(using=using)
                                if show_traceback:
                                    traceback.print_exc()
                                else:
                                    self.stderr.write(
                                        self.style.ERROR("Problem installing fixture '%s': %s\n" %
                                             (full_path, ''.join(traceback.format_exception(sys.exc_type,
                                                 sys.exc_value, sys.exc_traceback)))))
                                return
                            fixture.close()

                            # If the fixture we loaded contains 0 objects, assume that an
                            # error was encountered during fixture loading.
                            if objects_in_fixture == 0:
                                self.stderr.write(
                                    self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)\n" %
                                        (fixture_name)))
                                if commit:
                                    transaction.rollback(using=using)
                                    transaction.leave_transaction_management(using=using)
                                return

                    except Exception:
                        if verbosity >= 2:
                            self.stdout.write("No %s fixture '%s' in %s.\n" % \
                                (format, fixture_name, humanize(fixture_dir)))

        # If we found even one object in a fixture, we need to reset the
        # database sequences.
        if loaded_object_count > 0:
            sequence_sql = connection.ops.sequence_reset_sql(self.style, models)
            if sequence_sql:
                if verbosity >= 2:
                    self.stdout.write("Resetting sequences\n")
                for line in sequence_sql:
                    cursor.execute(line)

        if commit:
            transaction.commit(using=using)
            transaction.leave_transaction_management(using=using)

        if fixture_object_count == 0:
            if verbosity >= 1:
                self.stdout.write("No fixtures found.\n")
        else:
            if verbosity >= 1:
                if fixture_object_count == loaded_object_count:
                    self.stdout.write("Installed %d object(s) from %d fixture(s)\n" % (
                        loaded_object_count, fixture_count))
                else:
                    self.stdout.write("Installed %d object(s) (of %d) from %d fixture(s)\n" % (
                        loaded_object_count, fixture_object_count, fixture_count))

        # Close the DB connection. 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 commit:
            connection.close()
Example #11
0
    def handle(self, *fixture_labels, **options):
        using = options.get('database')

        connection = connections[using]
        self.style = no_style()

        if not len(fixture_labels):
            self.stderr.write(
                self.style.ERROR(
                    "No database fixture specified. Please provide the path of at least one fixture in the command line.\n"
                ))
            return

        verbosity = int(options.get('verbosity'))
        show_traceback = options.get('traceback')

        # commit is a stealth option - it isn't really useful as
        # a command line option, but it can be useful when invoking
        # loaddata from within another script.
        # If commit=True, loaddata will use its own transaction;
        # if commit=False, the data load SQL will become part of
        # the transaction in place when loaddata was invoked.
        commit = options.get('commit', True)

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: "'%s'" % dirname if dirname else 'absolute path'

        # Get a cursor (even though we don't need one yet). This has
        # the side effect of initializing the test database (if
        # it isn't already initialized).
        cursor = connection.cursor()

        # Start transaction management. All fixtures are installed in a
        # single transaction to ensure that all references are resolved.
        if commit:
            transaction.commit_unless_managed(using=using)
            transaction.enter_transaction_management(using=using)
            transaction.managed(True, using=using)

        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(
                        self.namelist()
                    ) == 1, "Zip-compressed fixtures must contain only one file."

            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None: open,
            'gz': gzip.GzipFile,
            'zip': SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [
            os.path.join(os.path.dirname(path), 'fixtures')
            for path in app_module_paths
        ]

        try:
            with connection.constraint_checks_disabled():
                for fixture_label in fixture_labels:
                    parts = fixture_label.split('.')

                    if len(parts) > 1 and parts[-1] in compression_types:
                        compression_formats = [parts[-1]]
                        parts = parts[:-1]
                    else:
                        compression_formats = compression_types.keys()

                    if len(parts) == 1:
                        fixture_name = parts[0]
                        formats = serializers.get_public_serializer_formats()
                    else:
                        fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                        if format in serializers.get_public_serializer_formats(
                        ):
                            formats = [format]
                        else:
                            formats = []

                    if formats:
                        if verbosity >= 2:
                            self.stdout.write("Loading '%s' fixtures...\n" %
                                              fixture_name)
                    else:
                        self.stderr.write(
                            self.style.ERROR(
                                "Problem installing fixture '%s': %s is not a known serialization format.\n"
                                % (fixture_name, format)))
                        if commit:
                            transaction.rollback(using=using)
                            transaction.leave_transaction_management(
                                using=using)
                        return

                    if os.path.isabs(fixture_name):
                        fixture_dirs = [fixture_name]
                    else:
                        fixture_dirs = app_fixtures + list(
                            settings.FIXTURE_DIRS) + ['']

                    for fixture_dir in fixture_dirs:
                        if verbosity >= 2:
                            self.stdout.write("Checking %s for fixtures...\n" %
                                              humanize(fixture_dir))

                        label_found = False
                        for combo in product([using, None], formats,
                                             compression_formats):
                            database, format, compression_format = combo
                            file_name = '.'.join(p for p in [
                                fixture_name, database, format,
                                compression_format
                            ] if p)

                            if verbosity >= 3:
                                self.stdout.write("Trying %s for %s fixture '%s'...\n" %\
                                                  (humanize(fixture_dir), file_name, fixture_name))
                            full_path = os.path.join(fixture_dir, file_name)
                            open_method = compression_types[compression_format]
                            try:
                                fixture = open_method(full_path, 'r')
                            except IOError:
                                if verbosity >= 2:
                                    self.stdout.write("No %s fixture '%s' in %s.\n" %\
                                                      (format, fixture_name, humanize(fixture_dir)))
                            else:
                                try:
                                    if label_found:
                                        self.stderr.write(
                                            self.style.ERROR(
                                                "Multiple fixtures named '%s' in %s. Aborting.\n"
                                                % (fixture_name,
                                                   humanize(fixture_dir))))
                                        if commit:
                                            transaction.rollback(using=using)
                                            transaction.leave_transaction_management(
                                                using=using)
                                        return

                                    fixture_count += 1
                                    objects_in_fixture = 0
                                    loaded_objects_in_fixture = 0
                                    if verbosity >= 2:
                                        self.stdout.write("Installing %s fixture '%s' from %s.\n" %\
                                                          (format, fixture_name, humanize(fixture_dir)))

                                    objects = serializers.deserialize(
                                        format, fixture, using=using)

                                    object_write_buffer = {}
                                    for obj in objects:
                                        objects_in_fixture += 1
                                        if router.allow_syncdb(
                                                using, obj.object.__class__):
                                            loaded_objects_in_fixture += 1
                                            models.add(obj.object.__class__)
                                            try:
                                                obj.save(using=using)
                                                #todo The commented code below (and after the except) should activate an alternative save that is done in bulk. Not working yet...
#                                                the_model = type(obj.object)
#                                                if the_model not in object_write_buffer:
#                                                    object_write_buffer.update({the_model:[]})
#                                                item = {}
#                                                item.update( {'account':obj.object.account})
#                                                for field in obj.object._meta.fields:
#                                                    item.update( {field.attname : getattr(obj.object, field.attname ) } )
#                                                object_write_buffer[the_model].append(item)
#                                                if len(object_write_buffer[the_model]) > 500:
#                                                    the_model.objects.bulk_insert(object_write_buffer[the_model])
#                                                    object_write_buffer[the_model]=[]
                                            except (DatabaseError,
                                                    IntegrityError), e:
                                                msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
                                                    'app_label':
                                                    obj.object._meta.app_label,
                                                    'object_name':
                                                    obj.object._meta.
                                                    object_name,
                                                    'pk':
                                                    obj.object.pk,
                                                    'error_msg':
                                                    e
                                                }
                                                raise e.__class__, e.__class__(
                                                    msg), sys.exc_info()[2]

#                                    for the_model in object_write_buffer.keys():
#                                        if len(object_write_buffer[the_model]) > 0:
#                                            the_model.objects.bulk_insert(object_write_buffer[the_model])
#                                            object_write_buffer[the_model]=[]

                                    loaded_object_count += loaded_objects_in_fixture
                                    fixture_object_count += objects_in_fixture
                                    label_found = True
                                finally:
                                    fixture.close()

                                # If the fixture we loaded contains 0 objects, assume that an
                                # error was encountered during fixture loading.
                                if objects_in_fixture == 0:
                                    self.stderr.write(
                                        self.style.ERROR(
                                            "No fixture data found for '%s'. (File format may be invalid.)\n"
                                            % (fixture_name)))
                                    if commit:
                                        transaction.rollback(using=using)
                                        transaction.leave_transaction_management(
                                            using=using)
                                    return

        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception:
            if commit:
                transaction.rollback(using=using)
                transaction.leave_transaction_management(using=using)
            if show_traceback:
                traceback.print_exc()
            else:
                self.stderr.write(
                    self.style.ERROR("Problem installing fixture '%s': %s\n" %
                                     (full_path, ''.join(
                                         traceback.format_exception(
                                             sys.exc_type, sys.exc_value,
                                             sys.exc_traceback)))))
            return

        # If we found even one object in a fixture, we need to reset the
        # database sequences.
        if loaded_object_count > 0:
            sequence_sql = connection.ops.sequence_reset_sql(
                self.style, models)
            if sequence_sql:
                if verbosity >= 2:
                    self.stdout.write("Resetting sequences\n")
                for line in sequence_sql:
                    cursor.execute(line)

        if commit:
            transaction.commit(using=using)
            transaction.leave_transaction_management(using=using)

        if verbosity >= 1:
            if fixture_object_count == loaded_object_count:
                self.stdout.write(
                    "Installed %d object(s) from %d fixture(s)\n" %
                    (loaded_object_count, fixture_count))
            else:
                self.stdout.write(
                    "Installed %d object(s) (of %d) from %d fixture(s)\n" %
                    (loaded_object_count, fixture_object_count, fixture_count))

        # Close the DB connection. 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 commit:
            connection.close()
Example #12
0
def tables_used_by_fixtures(fixture_labels, using=DEFAULT_DB_ALIAS):
    """Act like Django's stock loaddata command, but, instead of loading data,
    return an iterable of the names of the tables into which data would be
    loaded."""
    # Keep a count of the installed objects and fixtures
    fixture_count = 0
    loaded_object_count = 0
    fixture_object_count = 0
    tables = set()

    class SingleZipReader(zipfile.ZipFile):
        def __init__(self, *args, **kwargs):
            zipfile.ZipFile.__init__(self, *args, **kwargs)
            if settings.DEBUG:
                assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
        def read(self):
            return zipfile.ZipFile.read(self, self.namelist()[0])

    compression_types = {
        None:   file,
        'gz':   gzip.GzipFile,
        'zip':  SingleZipReader
    }
    if has_bz2:
        compression_types['bz2'] = bz2.BZ2File

    app_module_paths = []
    for app in get_apps():
        if hasattr(app, '__path__'):
            # It's a 'models/' subpackage
            for path in app.__path__:
                app_module_paths.append(path)
        else:
            # It's a models.py module
            app_module_paths.append(app.__file__)

    app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]
    for fixture_label in fixture_labels:
        parts = fixture_label.split('.')

        if len(parts) > 1 and parts[-1] in compression_types:
            compression_formats = [parts[-1]]
            parts = parts[:-1]
        else:
            compression_formats = compression_types.keys()

        if len(parts) == 1:
            fixture_name = parts[0]
            formats = serializers.get_public_serializer_formats()
        else:
            fixture_name, format = '.'.join(parts[:-1]), parts[-1]
            if format in serializers.get_public_serializer_formats():
                formats = [format]
            else:
                formats = []

        if not formats:
            # stderr.write(style.ERROR("Problem installing fixture '%s': %s is
            # not a known serialization format.\n" % (fixture_name, format)))
            return set()

        if os.path.isabs(fixture_name):
            fixture_dirs = [fixture_name]
        else:
            fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']

        for fixture_dir in fixture_dirs:
            # stdout.write("Checking %s for fixtures...\n" %
            # humanize(fixture_dir))

            label_found = False
            for combo in product([using, None], formats, compression_formats):
                database, format, compression_format = combo
                file_name = '.'.join(
                    p for p in [
                        fixture_name, database, format, compression_format
                    ]
                    if p
                )

                # stdout.write("Trying %s for %s fixture '%s'...\n" % \
                # (humanize(fixture_dir), file_name, fixture_name))
                full_path = os.path.join(fixture_dir, file_name)
                open_method = compression_types[compression_format]
                try:
                    fixture = open_method(full_path, 'r')
                    if label_found:
                        fixture.close()
                        # stderr.write(style.ERROR("Multiple fixtures named
                        # '%s' in %s. Aborting.\n" % (fixture_name,
                        # humanize(fixture_dir))))
                        return set()
                    else:
                        fixture_count += 1
                        objects_in_fixture = 0
                        loaded_objects_in_fixture = 0
                        # stdout.write("Installing %s fixture '%s' from %s.\n"
                        # % (format, fixture_name, humanize(fixture_dir)))
                        try:
                            objects = serializers.deserialize(format, fixture, using=using)
                            for obj in objects:
                                objects_in_fixture += 1
                                if router.allow_syncdb(using, obj.object.__class__):
                                    loaded_objects_in_fixture += 1
                                    tables.add(
                                        obj.object.__class__._meta.db_table)
                            loaded_object_count += loaded_objects_in_fixture
                            fixture_object_count += objects_in_fixture
                            label_found = True
                        except (SystemExit, KeyboardInterrupt):
                            raise
                        except Exception:
                            fixture.close()
                            # stderr.write( style.ERROR("Problem installing
                            # fixture '%s': %s\n" % (full_path, ''.join(tra
                            # ceback.format_exception(sys.exc_type,
                            # sys.exc_value, sys.exc_traceback)))))
                            return set()
                        fixture.close()

                        # If the fixture we loaded contains 0 objects, assume that an
                        # error was encountered during fixture loading.
                        if objects_in_fixture == 0:
                            # stderr.write( style.ERROR("No fixture data found
                            # for '%s'. (File format may be invalid.)\n" %
                            # (fixture_name)))
                            return set()

                except Exception:
                    # stdout.write("No %s fixture '%s' in %s.\n" % \ (format,
                    # fixture_name, humanize(fixture_dir)))
                    pass

    return tables
Example #13
0
    def handle(self, *fixture_labels, **options):
        self.style = no_style()

        verbosity = int(options.get('verbosity', 1))
        show_traceback = options.get('traceback', False)
        
        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path'
        
        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])

        compression_types = {
            None:   file,
            'gz':   gzip.GzipFile,
            'zip':  SingleZipReader
        }
        if has_bz2:
            compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]
        for fixture_label in fixture_labels:
            parts = fixture_label.split('.')

            if len(parts) > 1 and parts[-1] in compression_types:
                compression_formats = [parts[-1]]
                parts = parts[:-1]
            else:
                compression_formats = compression_types.keys()

            if len(parts) == 1:
                fixture_name = parts[0]
                formats = serializers.get_public_serializer_formats()
            else:
                fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                if format in serializers.get_public_serializer_formats():
                    formats = [format]
                else:
                    formats = []

            if formats:
                if verbosity >= 2:
                    self.stdout.write("Loading '%s' fixtures...\n" % fixture_name)
            else:
                self.stderr.write(
                    self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" %
                        (fixture_name, format)))
                return

            if os.path.isabs(fixture_name):
                fixture_dirs = [fixture_name]
            else:
                fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']

            for fixture_dir in fixture_dirs:
                if verbosity >= 2:
                    self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))

                label_found = False
                for combo in product(formats, compression_formats):
                    format, compression_format = combo
                    file_name = '.'.join(
                        p for p in [
                            fixture_name, format, compression_format
                        ]
                        if p
                    )

                    if verbosity >= 3:
                        self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                            (humanize(fixture_dir), file_name, fixture_name))
                    full_path = os.path.join(fixture_dir, file_name)
                    open_method = compression_types[compression_format]
                    try:
                        fixture = open_method(full_path, 'r')
                        if label_found:
                            fixture.close()
                            self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" %
                                (fixture_name, humanize(fixture_dir))))
                            return
                        else:
                            fixture_count += 1
                            objects_in_fixture = 0
                            loaded_objects_in_fixture = 0
                            if verbosity >= 2:
                                self.stdout.write("Installing %s fixture '%s' from %s.\n" % \
                                    (format, fixture_name, humanize(fixture_dir)))
                            try:
                                objects = serializers.deserialize(format, fixture)
                                for obj in objects:
                                    objects_in_fixture += 1
                                    
                                    loaded_objects_in_fixture += 1
                                    models.add(obj.object.__class__)
                                    obj.save()
                                loaded_object_count += loaded_objects_in_fixture
                                fixture_object_count += objects_in_fixture
                                label_found = True
                            except (SystemExit, KeyboardInterrupt):
                                raise
                            except Exception:
                                import traceback
                                fixture.close()
                                if show_traceback:
                                    traceback.print_exc()
                                else:
                                    self.stderr.write(
                                        self.style.ERROR("Problem installing fixture '%s': %s\n" %
                                             (full_path, ''.join(traceback.format_exception(sys.exc_type,
                                                 sys.exc_value, sys.exc_traceback)))))
                                return
                            fixture.close()

                            # If the fixture we loaded contains 0 objects, assume that an
                            # error was encountered during fixture loading.
                            if objects_in_fixture == 0:
                                self.stderr.write(
                                    self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)\n" %
                                        (fixture_name)))
                                return

                    except Exception, e:
                        if verbosity >= 2:
                            self.stdout.write("No %s fixture '%s' in %s.\n" % \
                                (format, fixture_name, humanize(fixture_dir)))
Example #14
0
    def handle(self, *fixture_labels, **options):
        verbosity = int(options.get('verbosity', 1))
        show_traceback = options.get('traceback', False)
        commit = options.get('commit', True)
        self.style = no_style()
        session = orm.sessionmaker()

        # Keep a count of the installed objects and fixtures
        fixture_count = 0
        loaded_object_count = 0
        fixture_object_count = 0
        models = set()

        humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path'
        """
        class SingleZipReader(zipfile.ZipFile):
            def __init__(self, *args, **kwargs):
                zipfile.ZipFile.__init__(self, *args, **kwargs)
                if settings.DEBUG:
                    assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
            def read(self):
                return zipfile.ZipFile.read(self, self.namelist()[0])
        """
        compression_types = {
            None: file,
            #'gz':   gzip.GzipFile,
            #'zip':  SingleZipReader
        }
        #if has_bz2:
        #    compression_types['bz2'] = bz2.BZ2File

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') \
            for path in app_module_paths]
        for fixture_label in fixture_labels:
            parts = fixture_label.split('.')

            if len(parts) > 1 and parts[-1] in compression_types:
                compression_formats = [parts[-1]]
                parts = parts[:-1]
            else:
                compression_formats = compression_types.keys()

            if len(parts) == 1:
                fixture_name = parts[0]
                formats = serializers.get_public_serializer_formats()
            else:
                fixture_name, format = '.'.join(parts[:-1]), parts[-1]
                if format in serializers.get_public_serializer_formats():
                    formats = [format]
                else:
                    formats = []

            if formats:
                if verbosity >= 2:
                    self.stdout.write("Loading '%s' fixtures...\n" %
                                      fixture_name)
            else:
                self.stderr.write(
                    self.style.ERROR(
                        "Problem installing fixture '%s': %s is not a known serialization format.\n"
                        % (fixture_name, format)))
                if commit:
                    transaction.rollback(using=using)
                    transaction.leave_transaction_management(using=using)
                return

            if os.path.isabs(fixture_name):
                fixture_dirs = [fixture_name]
            else:
                fixture_dirs = app_fixtures + list(
                    settings.FIXTURE_DIRS) + ['']

            for fixture_dir in fixture_dirs:
                if verbosity >= 2:
                    self.stdout.write("Checking %s for fixtures...\n" %
                                      humanize(fixture_dir))

                label_found = False
                for combo in product([None], formats, compression_formats):
                    database, format, compression_format = combo
                    file_name = '.'.join(
                        p for p in
                        [fixture_name, database, format, compression_format]
                        if p)

                    if verbosity >= 3:
                        self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
                            (humanize(fixture_dir), file_name, fixture_name))
                    full_path = os.path.join(fixture_dir, file_name)
                    open_method = compression_types[compression_format]
                    try:
                        fixture = open_method(full_path, 'r')
                        if label_found:
                            fixture.close()
                            self.stderr.write(
                                self.style.ERROR(
                                    "Multiple "
                                    "fixtures named '%s' in %s. Aborting.\n" %
                                    (fixture_name, humanize(fixture_dir))))
                            if commit:
                                session.rollback()
                            return
                        else:
                            fixture_count += 1
                            objects_in_fixture = 0
                            loaded_objects_in_fixture = 0
                            if verbosity >= 2:
                                self.stdout.write("Installing %s fixture "
                                                  "'%s' from %s.\n" %
                                                  (format, fixture_name,
                                                   humanize(fixture_dir)))
                            try:
                                objects = serializers.deserialize(
                                    format, fixture)
                                for obj in objects:
                                    objects_in_fixture += 1
                                    loaded_objects_in_fixture += 1
                                    models.add(obj.__class__)
                                    session.add(obj)
                                    session.commit()
                                loaded_object_count += loaded_objects_in_fixture
                                fixture_object_count += objects_in_fixture
                                label_found = True
                                #session.commit()
                            except (SystemExit, KeyboardInterrupt):
                                raise
                            except Exception:
                                import traceback
                                fixture.close()
                                if commit:
                                    session.rollback()
                                if show_traceback:
                                    traceback.print_exc()
                                else:
                                    self.stderr.write(
                                        self.style.ERROR(
                                            "Problem installing "
                                            "fixture '%s': %s\n" %
                                            (full_path, ''.join(
                                                traceback.format_exception(
                                                    sys.exc_type,
                                                    sys.exc_value,
                                                    sys.exc_traceback)))))
                                return
                            fixture.close()
                            # If the fixture we loaded contains 0 objects, assume that an
                            # error was encountered during fixture loading.
                            if objects_in_fixture == 0:
                                self.stderr.write(
                                    self.style.ERROR("No fixture data found " \
                                        "for '%s'. (File format may be " \
                                        "invalid.)\n" % (fixture_name)))
                                if commit:
                                    session.rollback()
                                return

                    except Exception, e:
                        if verbosity >= 2:
                            self.stdout.write("No %s fixture '%s' in %s.\n" % \
                                (format, fixture_name, humanize(fixture_dir)))