django.db.utils.IntegrityError - python examples

Here are the examples of the python api django.db.utils.IntegrityError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

48 Examples 7

3 View Complete Implementation : test_models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
    def test_content_type_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')

        with self.astertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=None,
                object_id=europe.pk,
                field='name',
                language='de',
                text='Europa',
            )

        self.astertEqual(
            error.exception.args[0],
            ('NOT NULL constraint failed: translations_translation' +
             '.content_type_id'),
        )

3 View Complete Implementation : test_models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
    def test_object_id_none(self):
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.astertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=None,
                field='name',
                language='de',
                text='Europa',
            )

        self.astertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.object_id',
        )

3 View Complete Implementation : test_models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
    def test_content_object_none(self):
        with self.astertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_object=None,
                field='name',
                language='de',
                text='Europa',
            )

        self.astertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.object_id',
        )

3 View Complete Implementation : test_models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
    def test_field_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.astertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field=None,
                language='de',
                text='Europa',
            )

        self.astertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.field',
        )

3 View Complete Implementation : test_models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
    def test_language_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.astertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field='name',
                language=None,
                text='Europa',
            )

        self.astertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.language',
        )

3 View Complete Implementation : test_models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
    def test_text_none(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)

        with self.astertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field='name',
                language='de',
                text=None,
            )

        self.astertEqual(
            error.exception.args[0],
            'NOT NULL constraint failed: translations_translation.text',
        )

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def execute(self, query, args=None):
        try:
            return self.cursor.execute(query, args)
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclastified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclastified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def execute(self, query, args=None):
        try:
            return self.cursor.execute(query, args)
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.IntegrityError as e:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def execute(self, query, params=()):
        query = self.convert_query(query)
        try:
            return Database.Cursor.execute(self, query, params)
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def executemany(self, query, param_list):
        query = self.convert_query(query)
        try:
            return Database.Cursor.executemany(self, query, param_list)
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

3 View Complete Implementation : base.py
Copyright MIT License
Author : bpgc-cte
    def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.DatabaseError as e:
                # cx_Oracle raises a cx_Oracle.DatabaseError exception
                # with the following attributes and values:
                #  code = 2091
                #  message = 'ORA-02091: transaction rolled back
                #            'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
                #               _C00102056) violated - parent key not found'
                # We convert that particular case to our IntegrityError exception
                x = e.args[0]
                if hasattr(x, 'code') and hasattr(x, 'message') \
                   and x.code == 2091 and 'ORA-02291' in x.message:
                    six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
                raise

3 View Complete Implementation : models.py
Copyright MIT License
Author : coogger
@receiver(m2m_changed, sender=Follow.following.through)
def verify_follow_m2m(sender, **kwargs):
    oiou = kwargs.get("instance", None)
    action = kwargs.get("action", None)
    following = kwargs.get("pk_set", None)
    if action == "pre_add":
        for following_user_id in following:
            if following_user_id == oiou.user.id:
                raise IntegrityError("Can not be follow yourself")
            elif Follow.objects.filter(user=oiou.user).filter(
                following=following_user_id
            ):
                raise IntegrityError(
                    f"Follow with user {oiou.user}\
                      already exists for publisher {Follow.objects.get(user=oiou.user)}"
                )

3 View Complete Implementation : models.py
Copyright MIT License
Author : coogger
@receiver(m2m_changed, sender=DjangoViews.ips.through)
def verify_views_m2m(sender, **kwargs):
    instance = kwargs.get("instance", None)
    action = kwargs.get("action", None)
    ips = kwargs.get("pk_set", None)
    if action == "pre_add":
        for ip_id in ips:
            model = DjangoViews
            query = model.objects.filter(
                content_type=instance.content_type, object_id=instance.object_id
            )
            if query.filter(ips=ip_id).exists():
                raise IntegrityError(
                    f"<Already save {instance.content_type.model} id:{instance.object_id}>"
                )
    instance.views_count = instance.ips.all().count()
    instance.save(update_fields=["views_count"])

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : drexly
    def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.DatabaseError as e:
                # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
                # with the following attributes and values:
                #  code = 2091
                #  message = 'ORA-02091: transaction rolled back
                #            'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
                #               _C00102056) violated - parent key not found'
                # We convert that particular case to our IntegrityError exception
                x = e.args[0]
                if hasattr(x, 'code') and hasattr(x, 'message') \
                   and x.code == 2091 and 'ORA-02291' in x.message:
                    six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
                raise

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : drexly
    def execute(self, query, params=None):
        query, params = self._fix_for_params(query, params)
        self._guess_input_sizes([params])
        try:
            return self.cursor.execute(query, self._param_generator(params))
        except Database.DatabaseError as e:
            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : drexly
    def executemany(self, query, params=None):
        if not params:
            # No params given, nothing to do
            return None
        # uniform treatment for sequences and iterables
        params_iter = iter(params)
        query, firstparams = self._fix_for_params(query, next(params_iter))
        # we build a list of formatted params; as we're going to traverse it
        # more than once, we can't make it lazy by using a generator
        formatted = [firstparams] + [self._format_params(p) for p in params_iter]
        self._guess_input_sizes(formatted)
        try:
            return self.cursor.executemany(query,
                                [self._param_generator(p) for p in formatted])
        except Database.DatabaseError as e:
            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def execute(self, query, args=None):
        try:
            # args is None means no string interpolation
            # sql_statment = str(query).lower()
            # c_time = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
            # if 'select' not in sql_statment and 'homepublishedvideo' in sql_statment:
            #     print 'search_sql', c_time, query, args
            return self.cursor.execute(query, args)
        except Database.OperationalError as e:
            # CR_SERVER_GONE_ERROR, CR_SERVER_LOST
            if e.args[0] in (2006, 2013):
                from django.db import close_old_connections
                close_old_connections()
            # Map some error codes to IntegrityError, since they seem to be
            # misclastified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.OperationalError as e:
            if e.args[0] in (2006, 2013):
                from django.db import close_old_connections
                close_old_connections()
            # Map some error codes to IntegrityError, since they seem to be
            # misclastified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def executemany(self, query, params=None):
        if not params:
            # No params given, nothing to do
            return None
        # uniform treatment for sequences and iterables
        params_iter = iter(params)
        query, firstparams = self._fix_for_params(query, next(params_iter))
        # we build a list of formatted params; as we're going to traverse it
        # more than once, we can't make it lazy by using a generator
        formatted = [firstparams]+[self._format_params(p) for p in params_iter]
        self._guess_input_sizes(formatted)
        try:
            return self.cursor.executemany(query,
                                [self._param_generator(p) for p in formatted])
        except Database.DatabaseError as e:
            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

3 View Complete Implementation : routers.py
Copyright MIT License
Author : ex-ut
    def _get_horizontal_index(self, model, hints):
        horizontal_group = get_group_from_model(model)
        if not horizontal_group:
            return

        horizontal_key = hints.get('horizontal_key', None)
        if not horizontal_key:
            instance = hints.get('instance', None)
            if instance and isinstance(instance, model):
                return instance._horizontal_database_index
            return None

        if not horizontal_key:
            raise IntegrityError("Missing 'horizontal_key'")
        return get_or_create_index(model, horizontal_key)

3 View Complete Implementation : app.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def save(self, *args, **kwargs):    # pylint: disable=arguments-differ
        if APP.valid_objects.filter(uid=self.uid).exclude(pk=self.pk).exists():
            msg = "UNIQUE constraint failed: " \
                "oneid_meta.APP UniqueConstraint(fields=['uid'], condition=Q(is_del='False')"
            raise IntegrityError(msg)

        super(APP, self).save(*args, **kwargs)

3 View Complete Implementation : dept.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def save(self, *args, **kwargs):    # pylint: disable=arguments-differ
        if Dept.valid_objects.filter(uid=self.uid).exclude(pk=self.pk).exists():
            msg = "UNIQUE constraint failed: " \
                "oneid_meta.Dept UniqueConstraint(fields=['uid'], condition=Q(is_del='False')"
            raise IntegrityError(msg)

        super(Dept, self).save(*args, **kwargs)

3 View Complete Implementation : group.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def save(self, *args, **kwargs):    # pylint: disable=arguments-differ
        if Group.valid_objects.filter(uid=self.uid).exclude(pk=self.pk).exists():
            msg = "UNIQUE constraint failed: " \
                "oneid_meta.Group UniqueConstraint(fields=['uid'], condition=Q(is_del='False')"
            raise IntegrityError(msg)
        super(Group, self).save(*args, **kwargs)

3 View Complete Implementation : test_basic.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def test_group_union_unique(self):
        user = User.create_user('user', 'user')
        group = Group.valid_objects.create(uid='group')

        GroupMember.valid_objects.create(owner=group, user=user)

        with self.astertRaises(db.utils.IntegrityError):
            GroupMember.valid_objects.create(owner=group, user=user)

3 View Complete Implementation : test_basic.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def test_dept_union_unique(self):
        user = User.create_user('user', 'user')
        dept = Dept.valid_objects.create(uid='dept')

        DeptMember.valid_objects.create(owner=dept, user=user)

        with self.astertRaises(db.utils.IntegrityError):
            DeptMember.valid_objects.create(owner=dept, user=user)

3 View Complete Implementation : test_basic.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def test_valid_group_uid_unique(self):
        group = Group.valid_objects.create(uid='group')
        with self.astertRaises(db.utils.IntegrityError):
            group = Group.valid_objects.create(uid='group')

        group.name = 'name'
        group.save()

        group.delete()
        Group.valid_objects.create(uid='group')

        self.astertEqual(Group.objects.filter(uid='group').count(), 2)

3 View Complete Implementation : pipelines.py
Copyright MIT License
Author : richshaw2015
    def process_item(self, item, spider):
        site = Site.objects.get(name=item['name'])

        if site.status == 'active':
            try:
                article = Article(site=site, satle=item['satle'], uindex=current_ts(), content=item['content'],
                                  remark='', src_url=item['url'], author=item.get('author'))
                article.save()

                spider.logger.info(f"Insert to DB:`{item['satle']}`{item['url']}")

                # mark status
                mark_crawled_url(item['url'], item['req_url'])
            except django.db.utils.IntegrityError:
                # repeat item
                mark_crawled_url(item['url'], item['req_url'])

3 View Complete Implementation : base.py
Copyright MIT License
Author : rizwansoaib
    def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.DatabaseError as e:
                # cx_Oracle raises a cx_Oracle.DatabaseError exception
                # with the following attributes and values:
                #  code = 2091
                #  message = 'ORA-02091: transaction rolled back
                #            'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
                #               _C00102056) violated - parent key not found'
                # We convert that particular case to our IntegrityError exception
                x = e.args[0]
                if hasattr(x, 'code') and hasattr(x, 'message') \
                   and x.code == 2091 and 'ORA-02291' in x.message:
                    raise utils.IntegrityError(*tuple(e.args))
                raise

3 View Complete Implementation : models.py
Copyright MIT License
Author : skorokithakis
    def create(self, *args, **kwargs):
        """Generate an object, retrying if there's an ID collision."""
        # Try to generate new IDs for the object if one collides.
        tries = 10
        for x in range(tries):
            try:
                obj = super().create(*args, **kwargs)
            except IntegrityError:
                continue
            else:
                break
        else:
            raise IntegrityError("Could not find an ID after %s tries." % tries)

        return obj

0 View Complete Implementation : test_models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
    def test_uniqueness(self):
        europe = Continent.objects.create(name='Europe', code='EU')
        continent_ct = ContentType.objects.get_for_model(Continent)
        Translation.objects.create(
            content_type=continent_ct,
            object_id=europe.pk,
            field='name',
            language='de',
            text='Europa'
        )

        with self.astertRaises(utils.IntegrityError) as error:
            Translation.objects.create(
                content_type=continent_ct,
                object_id=europe.pk,
                field='name',
                language='de',
                text='Europa'
            )

        self.astertEqual(
            error.exception.args[0],
            ('UNIQUE constraint failed: ' +
             'translations_translation.content_type_id, ' +
             'translations_translation.object_id, ' +
             'translations_translation.field, ' +
             'translations_translation.language'),
        )

0 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def check_constraints(self, table_names=None):
        """
        Checks each table name in `table_names` for rows with invalid foreign key references. This method is
        intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while constraint checks were off.

        Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
        detailed information about the invalid reference in the error message.

        Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
        ALL IMMEDIATE")
        """
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor, table_name)
            for column_name, referenced_table_name, referenced_column_name in key_columns:
                cursor.execute("""
                    SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
                    LEFT JOIN `%s` as REFERRED
                    ON (REFERRING.`%s` = REFERRED.`%s`)
                    WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
                    % (primary_key_column_name, column_name, table_name, referenced_table_name,
                    column_name, referenced_column_name, column_name, referenced_column_name))
                for bad_row in cursor.fetchall():
                    raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
                        "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
                        % (table_name, bad_row[0],
                        table_name, column_name, bad_row[1],
                        referenced_table_name, referenced_column_name))

0 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.IntegrityError as e:
                # In case cx_Oracle implements (now or in a future version)
                # raising this specific exception
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            except Database.DatabaseError as e:
                # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
                # with the following attributes and values:
                #  code = 2091
                #  message = 'ORA-02091: transaction rolled back
                #            'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
                #               _C00102056) violated - parent key not found'
                # We convert that particular case to our IntegrityError exception
                x = e.args[0]
                if hasattr(x, 'code') and hasattr(x, 'message') \
                   and x.code == 2091 and 'ORA-02291' in x.message:
                    six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
                six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

0 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def execute(self, query, params=None):
        if params is None:
            params = []
        else:
            params = self._format_params(params)
        args = [(':arg%d' % i) for i in range(len(params))]
        # cx_Oracle wants no trailing ';' for SQL statements.  For PL/SQL, it
        # it does want a trailing ';' but not a trailing '/'.  However, these
        # characters must be included in the original query in case the query
        # is being pasted to SQL*Plus.
        if query.endswith(';') or query.endswith('/'):
            query = query[:-1]
        query = convert_unicode(query % tuple(args), self.charset)
        self._guess_input_sizes([params])
        try:
            return self.cursor.execute(query, self._param_generator(params))
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

0 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def executemany(self, query, params=None):
        # cx_Oracle doesn't support iterators, convert them to lists
        if params is not None and not isinstance(params, (list, tuple)):
            params = list(params)
        try:
            args = [(':arg%d' % i) for i in range(len(params[0]))]
        except (IndexError, TypeError):
            # No params given, nothing to do
            return None
        # cx_Oracle wants no trailing ';' for SQL statements.  For PL/SQL, it
        # it does want a trailing ';' but not a trailing '/'.  However, these
        # characters must be included in the original query in case the query
        # is being pasted to SQL*Plus.
        if query.endswith(';') or query.endswith('/'):
            query = query[:-1]
        query = convert_unicode(query % tuple(args), self.charset)
        formatted = [self._format_params(i) for i in params]
        self._guess_input_sizes(formatted)
        try:
            return self.cursor.executemany(query,
                                [self._param_generator(p) for p in formatted])
        except Database.IntegrityError as e:
            six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
        except Database.DatabaseError as e:
            # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
            if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])

0 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def check_constraints(self, table_names=None):
        """
        Checks each table name in `table_names` for rows with invalid foreign key references. This method is
        intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while constraint checks were off.

        Raises an IntegrityError on the first invalid foreign key reference encountered (if any) and provides
        detailed information about the invalid reference in the error message.

        Backends can override this method if they can more directly apply constraint checking (e.g. via "SET CONSTRAINTS
        ALL IMMEDIATE")
        """
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor, table_name)
            for column_name, referenced_table_name, referenced_column_name in key_columns:
                cursor.execute("""
                    SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
                    LEFT JOIN `%s` as REFERRED
                    ON (REFERRING.`%s` = REFERRED.`%s`)
                    WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL"""
                    % (primary_key_column_name, column_name, table_name, referenced_table_name,
                    column_name, referenced_column_name, column_name, referenced_column_name))
                for bad_row in cursor.fetchall():
                    raise utils.IntegrityError("The row in table '%s' with primary key '%s' has an invalid "
                        "foreign key: %s.%s contains a value '%s' that does not have a corresponding value in %s.%s."
                        % (table_name, bad_row[0], table_name, column_name, bad_row[1],
                        referenced_table_name, referenced_column_name))

0 View Complete Implementation : utilities.py
Copyright Apache License 2.0
Author : chris104957
def create_scheduled_task(task: Union[str, Callable],
                          interval: Dict[str, int],
                          task_name: str = None,
                          queue: str = None,
                          **kwargs) -> ScheduledTask:
    """
    Helper function for creating a :clast:`carrot.models.ScheduledTask`
    """

    if not task_name:
        if isinstance(task, str):
            task_name = task
        else:
            raise Exception('You must provide a task_name or task')

    task = validate_task(task)

    try:
        astert isinstance(interval, dict)
        astert len(interval.items()) == 1
    except astertionError:
        raise AttributeError('Interval must be a dict with a single key value pairing, e.g.: {\'seconds\': 5}')

    interval_type, count = list(*interval.items())

    try:
        t = ScheduledTask.objects.create(
                queue=queue,
                task_name=task_name,
                interval_type=interval_type,
                interval_count=count,
                routing_key=queue,
                task=task,
                content=json.dumps(kwargs or '{}'),
        )
    except IntegrityError:
        raise IntegrityError('A ScheduledTask with this task_name already exists. Please specific a unique name using '
                             'the task_name parameter')

    return t

0 View Complete Implementation : tasks.py
Copyright MIT License
Author : LexPredict
def create_filing_error(row, filing_path: str):
    """
    Create a Filing error record from an index row.
    :param row:
    :param filing_path:
    :return:
    """
    # Get vars
    cik = row["CIK"]
    company_name = row["Company Name"]
    form_type = row["Form Type"]

    try:
        date_filed = dateutil.parser.parse(str(row["Date Filed"])).date()
    except ValueError:
        date_filed = None
    except IndexError:
        date_filed = None

    # Create empty error filing record
    filing = Filing()
    filing.form_type = form_type
    filing.date_filed = date_filed
    filing.s3_path = filing_path
    filing.is_error = True
    filing.is_processed = False

    # Get company info
    try:
        company = Company.objects.get(cik=cik)

        try:
            _ = CompanyInfo.objects.get(company=company, date=date_filed)
        except CompanyInfo.DoesNotExist:
            # Create company info record
            company_info = CompanyInfo()
            company_info.company = company
            company_info.name = company_name
            company_info.sic = None
            company_info.state_incorporation = None
            company_info.state_location = None
            company_info.date = date_filed
            company_info.save()
    except Company.DoesNotExist:
        # Create company
        company = Company()
        company.cik = cik

        try:
            company.save()
        except django.db.utils.IntegrityError:
            return create_filing_error(row, filing_path)

        # Create company info record
        company_info = CompanyInfo()
        company_info.company = company
        company_info.name = company_name
        company_info.sic = None
        company_info.state_incorporation = None
        company_info.state_location = None
        company_info.date = date_filed
        company_info.save()

    # Finally update company and save
    filing.company = company
    filing.save()
    return True

0 View Complete Implementation : tasks.py
Copyright MIT License
Author : LexPredict
@shared_task
def process_filing(client, file_path: str, filing_buffer: Union[str, bytes] = None, store_raw: bool = False,
                   store_text: bool = False):
    """
    Process a filing from a path or filing buffer.
    :param file_path: path to process; if filing_buffer is none, retrieved from here
    :param filing_buffer: buffer; if not present, s3_path must be set
    :param store_raw:
    :param store_text:
    :return:
    """
    # Log entry
    logger.info("Processing filing {0}...".format(file_path))


    # Check for existing record first
    try:
        filing = Filing.objects.get(s3_path=file_path)
        if filing is not None:
            logger.error("Filing {0} has already been created in record {1}".format(file_path, filing))
            return None
    except Filing.DoesNotExist:
        logger.info("No existing record found.")
    except Filing.MultipleObjectsReturned:
        logger.error("Multiple existing record found.")
        return None

    # Get buffer
    if filing_buffer is None:
        logger.info("Retrieving filing buffer from S3...")
        filing_buffer = client.get_buffer(file_path)

    # Get main filing data structure
    filing_data = openedgar.parsers.edgar.parse_filing(filing_buffer, extract=store_text)
    if filing_data["cik"] is None:
        logger.error("Unable to parse CIK from filing {0}; astuming broken and halting...".format(file_path))
        return None

    try:
        # Get company
        company = Company.objects.get(cik=filing_data["cik"])
        logger.info("Found existing company record.")

        # Check if record exists for date
        try:
            _ = CompanyInfo.objects.get(company=company, date=filing_data["date_filed"])

            logger.info("Found existing company info record.")
        except CompanyInfo.DoesNotExist:
            # Create company info record
            company_info = CompanyInfo()
            company_info.company = company
            company_info.name = filing_data["company_name"]
            company_info.sic = filing_data["sic"]
            company_info.state_incorporation = filing_data["state_incorporation"]
            company_info.state_location = filing_data["state_location"]
            company_info.date = filing_data["date_filed"].date() if isinstance(filing_data["date_filed"],
                                                                               datetime.datetime) else \
                filing_data["date_filed"]
            company_info.save()

            logger.info("Created new company info record.")

    except Company.DoesNotExist:
        # Create company
        company = Company()
        company.cik = filing_data["cik"]

        try:
            # Catch race with another task/thread
            company.save()

            try:
                _ = CompanyInfo.objects.get(company=company, date=filing_data["date_filed"])
            except CompanyInfo.DoesNotExist:
                # Create company info record
                company_info = CompanyInfo()
                company_info.company = company
                company_info.name = filing_data["company_name"]
                company_info.sic = filing_data["sic"]
                company_info.state_incorporation = filing_data["state_incorporation"]
                company_info.state_location = filing_data["state_location"]
                company_info.date = filing_data["date_filed"]
                company_info.save()
        except django.db.utils.IntegrityError:
            company = Company.objects.get(cik=filing_data["cik"])

        logger.info("Created company and company info records.")

    # Now create the filing record
    try:
        filing = Filing()
        filing.form_type = filing_data["form_type"]
        filing.accession_number = filing_data["accession_number"]
        filing.date_filed = filing_data["date_filed"]
        filing.docameent_count = filing_data["docameent_count"]
        filing.company = company
        filing.sha1 = hashlib.sha1(filing_buffer).hexdigest()
        filing.s3_path = file_path
        filing.is_processed = False
        filing.is_error = True
        filing.save()
    except Exception as e:  # pylint: disable=broad-except
        logger.error("Unable to create filing record: {0}".format(e))
        return None

    # Create filing docameent records
    try:
        create_filing_docameents(client, filing_data["docameents"], filing, store_raw=store_raw, store_text=store_text)
        filing.is_processed = True
        filing.is_error = False
        filing.save()
        return filing
    except Exception as e:  # pylint: disable=broad-except
        logger.error("Unable to create filing docameents for {0}: {1}".format(filing, e))
        return None

0 View Complete Implementation : test_basic.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def test_trigger_perm_unique(self):
        Perm.valid_objects.create(uid='perm')
        with self.astertRaises(db.utils.IntegrityError):
            Perm.valid_objects.create(uid='perm')

0 View Complete Implementation : base.py
Copyright MIT License
Author : LuciferJack
    def check_constraints(self, table_names=None):
        """Check rows in tables for invalid foreign key references

        Checks each table name in `table_names` for rows with invalid foreign
        key references. This method is intended to be used in conjunction with
        `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while
        constraint checks were off.

        Raises an IntegrityError on the first invalid foreign key reference
        encountered (if any) and provides detailed information about the
        invalid reference in the error message.

        Backends can override this method if they can more directly apply
        constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE")
        """
        ref_query = """
            SELECT REFERRING.`{0}`, REFERRING.`{1}` FROM `{2}` as REFERRING
            LEFT JOIN `{3}` as REFERRED
            ON (REFERRING.`{4}` = REFERRED.`{5}`)
            WHERE REFERRING.`{6}` IS NOT NULL AND REFERRED.`{7}` IS NULL"""
        cursor = self.cursor()
        if table_names is None:
            table_names = self.introspection.table_names(cursor)
        for table_name in table_names:
            primary_key_column_name = \
                self.introspection.get_primary_key_column(cursor, table_name)
            if not primary_key_column_name:
                continue
            key_columns = self.introspection.get_key_columns(cursor,
                                                             table_name)
            for column_name, referenced_table_name, referenced_column_name \
                    in key_columns:
                cursor.execute(ref_query.format(primary_key_column_name,
                                                column_name, table_name,
                                                referenced_table_name,
                                                column_name,
                                                referenced_column_name,
                                                column_name,
                                                referenced_column_name))
                for bad_row in cursor.fetchall():
                    msg = ("The row in table '{0}' with primary key '{1}' has "
                           "an invalid foreign key: {2}.{3} contains a value "
                           "'{4}' that does not have a corresponding value in "
                           "{5}.{6}.".format(table_name, bad_row[0],
                                             table_name, column_name,
                                             bad_row[1], referenced_table_name,
                                             referenced_column_name))
                    raise utils.IntegrityError(msg)

0 View Complete Implementation : tests_Organization.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_name_should_be_uniq(self):
        o = Organization.objects.create(name="RAP")
        self.astertEqual(Organization.objects.count(), 1)
        self.astertRaises(django.db.utils.IntegrityError, Organization.objects.create, name="RAP")

0 View Complete Implementation : cron.py
Copyright MIT License
Author : richshaw2015
def update_all_user_feed():
    """
    更新所有 site
    """
    logger.info('开始运行定时更新RSS任务')

    now = datetime.now()

    # 按照不同频率更新
    if now.hour % 2 == 0:
        feeds = Site.objects.filter(status='active', creator='user').order_by('-star')
    elif now.hour % 2 == 1:
        feeds = Site.objects.filter(status='active', creator='user', star__gte=9).order_by('-star')

    for site in feeds:
        try:
            resp = requests.get(site.rss, timeout=30, verify=False)
        except:
            if site.star >= 9:
                logger.warning(f"RSS源可能失效了`{site.rss}")
            else:
                logger.info(f"RSS源可能失效了`{site.rss}")
            continue

        content = BytesIO(resp.content)
        feed_obj = feedparser.parse(content)

        max_count = 10
        if site.star < 20:
            max_count = 50

        for entry in feed_obj.entries[:max_count]:
            try:
                satle = entry.satle
                link = entry.link
            except AttributeError:
                logger.warning(f'必要属性获取失败:`{site.rss}')
                continue

            if is_crawled_url(link):
                continue

            try:
                author = entry['author'][:20]
            except:
                author = None

            try:
                value = entry.content[0].value
            except:
                value = entry.get('description') or entry.link

            # to absolute image url
            try:
                content_soup = BeautifulSoup(value, "html.parser")

                for img in content_soup.find_all('img'):
                    rel_src = img.attrs.get('src')
                    abs_src = urllib.parse.urljoin(link, rel_src)
                    img.attrs['src'] = abs_src

                value = str(content_soup)
            except:
                logger.warning(f'修复图片路径异常:`{satle}`{link}')

            try:
                article = Article(site=site, satle=satle, author=author, src_url=link, uindex=current_ts(),
                                  content=value)
                article.save()
                mark_crawled_url(link)
            except django.db.utils.IntegrityError:
                logger.info(f'数据重复插入:`{satle}`{link}')
            except:
                logger.warning(f'数据插入异常:`{satle}`{link}')

0 View Complete Implementation : views_api.py
Copyright MIT License
Author : richshaw2015
@verify_request
def submit_a_feed(request):
    """
    用户添加一个自定义的订阅源
    """
    feed_url = request.POST.get('url', '').strip()[:200]
    if feed_url:
        feed_obj = feedparser.parse(feed_url)
        if feed_obj.feed.get('satle'):
            name = get_hash_name(feed_url)
            cname = feed_obj.feed.satle[:20]

            if feed_obj.feed.get('link'):
                link = feed_obj.feed.link[:100]
            else:
                link = feed_url

            if feed_obj.feed.get('subsatle'):
                brief = feed_obj.feed.subsatle[:100]
            else:
                brief = cname

            author = feed_obj.feed.get('author', '')[:10]
            favicon = f"https://cdn.v2ex.com/gravatar/{name}?d=monsterid&s=64"

            try:
                site = Site(name=name, cname=cname, link=link, brief=brief, star=9, freq='小时', copyright=30, tag='RSS',
                            creator='user', rss=feed_url, favicon=favicon, author=author)
                site.save()
            except django.db.utils.IntegrityError:
                logger.warning(f"数据插入失败:`{feed_url}")
            return JsonResponse({"name": name})
        else:
            logger.warning(f"RSS解析失败:`{feed_url}")
    return HttpResponseNotFound("Param error")

0 View Complete Implementation : field.py
Copyright MIT License
Author : SectorLabs
    def validate(self, value: LocalizedValue, *_):
        """Validates that the values has been filled in for all required
        languages.

        Exceptions are raises in order to notify the user
        of invalid values.

        Arguments:
            value:
                The value to validate.
        """

        if self.null:
            return

        for lang in self.required:
            lang_val = getattr(value, settings.LANGUAGE_CODE)

            if lang_val is None:
                raise IntegrityError(
                    'null value in column "%s.%s" violates '
                    "not-null constraint" % (self.name, lang)
                )

0 View Complete Implementation : integer_field.py
Copyright MIT License
Author : SectorLabs
    def get_prep_value(self, value: LocalizedIntegerValue) -> dict:
        """Gets the value in a format to store into the database."""

        # apply default values
        default_values = LocalizedIntegerValue(self.default)
        if isinstance(value, LocalizedIntegerValue):
            for lang_code, _ in settings.LANGUAGES:
                local_value = value.get(lang_code)
                if local_value is None:
                    value.set(lang_code, default_values.get(lang_code, None))

        prepped_value = super().get_prep_value(value)
        if prepped_value is None:
            return None

        # make sure all values are proper integers
        for lang_code, _ in settings.LANGUAGES:
            local_value = prepped_value[lang_code]
            try:
                if local_value is not None:
                    int(local_value)
            except (TypeError, ValueError):
                raise IntegrityError(
                    'non-integer value in column "%s.%s" violates '
                    "integer constraint" % (self.name, lang_code)
                )

            # convert to a string before saving because the underlying
            # type is hstore, which only accept strings
            prepped_value[lang_code] = (
                str(local_value) if local_value is not None else None
            )

        return prepped_value