python类IntegrityError()的实例源码

base.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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

    # Oracle doesn't support releasing savepoints. But we fake them when query
    # logging is enabled to keep query counts consistent with other backends.
base.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
management.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as update_contenttypes will take care of asking the
                # user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
test_views.py 文件源码 项目:rovercode-web 作者: rovercode 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_rover_create(self):
        """Test the rover registration interface."""
        self.client.login(username='administrator', password='password')
        rover_info = {'name': 'Curiosity', 'local_ip': '192.168.0.10'}

        # Create the rover
        response = self.client.post(
            reverse('mission-control:rover-list'), rover_info)
        id = response.data['id']
        creation_time = dateutil.parser.parse(response.data['last_checkin'])
        self.assertEqual(response.status_code, 201)

        # Try and fail to create the same rover again
        with self.assertRaises(IntegrityError):
            self.client.post(reverse('mission-control:rover-list'), rover_info)

        # Update the rover
        response = self.client.put(
            reverse('mission-control:rover-detail', kwargs={'pk': id}),
            urlencode(rover_info),
            content_type="application/x-www-form-urlencoded"
        )
        checkin_time = dateutil.parser.parse(response.data['last_checkin'])
        self.assertEqual(response.status_code, 200)
        self.assertGreater(checkin_time, creation_time)
models.py 文件源码 项目:CoBL-public 作者: lingdb 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def merge_with(self, pk):
        obj = self.__class__.objects.get(pk=pk)
        for cj_obj in obj.cognacy:
            try:
                with transaction.atomic():
                    cj_obj.source = self
                    cj_obj.save()
            except IntegrityError:
                pass
        for cc_obj in obj.cogset:
            try:
                cc_obj.source = self
                cc_obj.save()
            except IntegrityError:
                pass
        for lc_obj in obj.lexeme:
            try:
                with transaction.atomic():
                    lc_obj.source = self
                    lc_obj.save()
            except IntegrityError:
                pass
        obj.delete()
__init__.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as remove_stale_contenttypes will take care of
                # asking the user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
base.py 文件源码 项目:python-mysql-pool 作者: LuciferJack 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _execute_wrapper(self, method, query, args):
        """Wrapper around execute() and executemany()"""
        try:
            return method(query, args)
        except (PyMysqlPool.mysql.connector.ProgrammingError) as err:
            six.reraise(utils.ProgrammingError,
                        utils.ProgrammingError(err.msg), sys.exc_info()[2])
        except (PyMysqlPool.mysql.connector.IntegrityError) as err:
            six.reraise(utils.IntegrityError,
                        utils.IntegrityError(err.msg), sys.exc_info()[2])
        except PyMysqlPool.mysql.connector.OperationalError as err:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if err.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError,
                            utils.IntegrityError(err.msg), sys.exc_info()[2])
            else:
                six.reraise(utils.DatabaseError,
                            utils.DatabaseError(err.msg), sys.exc_info()[2])
        except PyMysqlPool.mysql.connector.DatabaseError as err:
            six.reraise(utils.DatabaseError,
                        utils.DatabaseError(err.msg), sys.exc_info()[2])
lib.py 文件源码 项目:micromasters 作者: mitodl 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def update_fake_course_run_edx_key(user, course_run):
    """
    Convenience method to update a cached edX model based on the data from a CourseRun that was added
    by the seed_db command
    """
    start_date = course_run.start_date
    year = start_date.strftime('%Y')
    month = start_date.strftime('%B')
    short_month = month[:3]
    course_run.edx_course_key = re.sub(r'\w{3}_\d{4}$', '{}_{}'.format(short_month, year), course_run.edx_course_key)
    course_run.title = re.sub(r'\w+ \d{4}$', '{} {}'.format(month, year), course_run.title)
    try:
        course_run.save()
    except IntegrityError:
        # If another course run already has this edx key, just tack on the pk to the end
        course_run.edx_course_key = '{}({})'.format(course_run.edx_course_key, course_run.pk)
        course_run.title = '{} ({})'.format(course_run.title, course_run.pk)
        course_run.save()
    update_cached_edx_data_for_run(user, course_run)
    return course_run
__init__.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as remove_stale_contenttypes will take care of
                # asking the user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
views.py 文件源码 项目:Pyphon 作者: pyphonic 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def post(self, request, *args, **kwargs):
        """Post response."""
        self.form = self.get_form(self.form_class)
        number = request.POST['number']
        number, modified = validate_number(number)

        if self.form.is_valid() or modified:
            contact = Contact.objects.filter(id=kwargs["pk"]).first()
            contact.name = request.POST['name']
            contact.number = number
            try:
                contact.save()
            except IntegrityError:
                return self.get(request, *args, **kwargs)
            pk = contact.pk
            return redirect(reverse_lazy("contact_detail", kwargs={'pk': pk}))
        return self.get(request, *args, **kwargs)
base.py 文件源码 项目:importacsv 作者: rasertux 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _execute_wrapper(self, method, query, args):
        """Wrapper around execute() and executemany()"""
        try:
            return method(query, args)
        except (mysql.connector.ProgrammingError) as err:
            six.reraise(utils.ProgrammingError,
                        utils.ProgrammingError(err.msg), sys.exc_info()[2])
        except (mysql.connector.IntegrityError) as err:
            six.reraise(utils.IntegrityError,
                        utils.IntegrityError(err.msg), sys.exc_info()[2])
        except mysql.connector.OperationalError as err:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if err.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError,
                            utils.IntegrityError(err.msg), sys.exc_info()[2])
            else:
                six.reraise(utils.DatabaseError,
                            utils.DatabaseError(err.msg), sys.exc_info()[2])
        except mysql.connector.DatabaseError as err:
            six.reraise(utils.DatabaseError,
                        utils.DatabaseError(err.msg), sys.exc_info()[2])
test_django_fakery_factories.py 文件源码 项目:factory_audit 作者: jamescooke 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def test_default(self):
        """
        Django Fakery: User Model: YELLOW (raises IntegrityError)

        We have to push the number of Users created, but since Django Fakery
        has no collision protection and uses a small number of latin words it
        will always fail sooner or later. Sometimes on the second user.

        However, instances created are valid if they are able to enter the
        database.
        """
        with self.assertRaises(IntegrityError) as cm:
            for expected_num_created in range(1, 100):
                with transaction.atomic():
                    UserFactory()

        self.assertEqual(self.user_model.objects.count(), expected_num_created - 1)
        self.assertIn('unique', str(cm.exception).lower())
        for u in self.user_model.objects.all():
            u.full_clean()
test_model_mommy_factories.py 文件源码 项目:factory_audit 作者: jamescooke 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_default(self):
        """
        Model Mommy: Plant.Item: YELLOW (raises IntegrityError)

        There is no method used to create unique values so there are collisions
        when there are a small number of possible values. Items that are
        created are valid.
        """
        with self.assertRaises(IntegrityError) as cm:
            for expected_num_created in range(1, 25):
                with transaction.atomic():
                    ItemFactory()

        self.assertEqual(Item.objects.count(), expected_num_created - 1)
        self.assertIn('unique', str(cm.exception).lower())
        for item in Item.objects.all():
            item.full_clean()
management.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as update_contenttypes will take care of asking the
                # user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
base.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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

    # Oracle doesn't support releasing savepoints. But we fake them when query
    # logging is enabled to keep query counts consistent with other backends.
base.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:promgen 作者: line 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def post(self, request, pk):
        farm = get_object_or_404(models.Farm, id=pk)
        farm.source = discovery.FARM_DEFAULT

        try:
            farm.save()
        except IntegrityError:
            return render(request, 'promgen/farm_duplicate.html', {
                'pk': farm.pk,
                'next': request.POST.get('next', reverse('farm-detail', args=[farm.pk])),
                'farm_list': models.Farm.objects.filter(name=farm.name)
            })

        return HttpResponseRedirect(
            request.POST.get('next', reverse('farm-detail', args=[farm.pk]))
        )
test_utils.py 文件源码 项目:daisychain 作者: daisychainme 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def create_twitter_channel():

        try:
            c = Channel(name="Twitter",
                        image="/static/channels/twitter.png",
                        color="#55acee",
                        font_color="#ffffff")
            c.save()
        except IntegrityError:
            return

        a = Action(channel=c,
                   action_type=100,
                   name="Post new status on Twitter")
        a.save()
        ActionInput(action=a, name="Status", mime_type="text").save()

        a = Action(channel=c,
                   action_type=101,
                   name="Post new photo on Twitter")
        a.save()
        ActionInput(action=a, name="Status", mime_type="text").save()
        ActionInput(action=a, name="Photo", mime_type="image").save()

        Action(channel=c, action_type=404, name="I dont have inputs").save()
base.py 文件源码 项目:trydjango18 作者: wei0104 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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

    # Oracle doesn't support releasing savepoints. But we fake them when query
    # logging is enabled to keep query counts consistent with other backends.
base.py 文件源码 项目:trydjango18 作者: wei0104 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
management.py 文件源码 项目:ims 作者: ims-team 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as update_contenttypes will take care of asking the
                # user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
__init__.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as remove_stale_contenttypes will take care of
                # asking the user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
base.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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

    # Oracle doesn't support releasing savepoints. But we fake them when query
    # logging is enabled to keep query counts consistent with other backends.
base.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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, Database.IntegrityError):
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise
management.py 文件源码 项目:django-open-lecture 作者: DmLitov4 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as update_contenttypes will take care of asking the
                # user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
management.py 文件源码 项目:travlr 作者: gauravkulkarni96 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as update_contenttypes will take care of asking the
                # user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
admin.py 文件源码 项目:djangoshop-shopit 作者: dinoperovic 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def create_variant(self, request, pk, combo, message=True, product=None, language=None):
        """
        This view creates a full variant with it's attribute values
        based on a combination index passed in as `combo`.
        """
        product = product or get_object_or_404(Product, pk=pk)
        product = product.group or product
        if not language:
            language = get_current_language()
        try:
            combo = product.get_combinations()[int(combo)]
            variant = product.create_variant(combo, language=language)
        except (IndexError, ObjectDoesNotExist, IntegrityError):
            return HttpResponseBadRequest()
        if message:
            messages.success(request, _('Variant successfully created.'))
        return HttpResponseRedirect(
            reverse('admin:shopit_product_change', args=[variant.pk]) + '?language=%s' % language)
__init__.py 文件源码 项目:liberator 作者: libscie 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _rename(self, apps, schema_editor, old_model, new_model):
        ContentType = apps.get_model('contenttypes', 'ContentType')
        db = schema_editor.connection.alias
        if not router.allow_migrate_model(db, ContentType):
            return

        try:
            content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model)
        except ContentType.DoesNotExist:
            pass
        else:
            content_type.model = new_model
            try:
                with transaction.atomic(using=db):
                    content_type.save(update_fields={'model'})
            except IntegrityError:
                # Gracefully fallback if a stale content type causes a
                # conflict as remove_stale_contenttypes will take care of
                # asking the user what should be done next.
                content_type.model = old_model
            else:
                # Clear the cache as the `get_by_natual_key()` call will cache
                # the renamed ContentType instance by its old model name.
                ContentType.objects.clear_cache()
models.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _create_user(self, email, password, is_staff,
                     is_superuser, is_active, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        try:
            now = timezone.now()
            if not email:
                raise ValueError('The given email must be set')
            email = self.normalize_email(email)
            user = self.model(email=email, is_staff=is_staff,
                              is_active=is_active, is_superuser=is_superuser,
                              date_joined=now, **extra_fields)
            user.set_password(password)
            user.save(using=self._db)
            return user
        except IntegrityError:
            _LOGGER.error('Cannot create new user with email %s. '
                         'A user with that email already exists.', email)
test_functional.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def test_integrity_error(self):
        """
        Tests the configuration test tool when an IntegrityError is raised.
        """
        self.page.config_test_value = 'test text'

        with patch('django.forms.ModelForm.save',
                   side_effect=IntegrityError('foo')):
            with LogCapture('cyphon.admin') as log_capture:

                actual = self.page.run_test()
                expected = "Could not create an object for testing: foo"
                self.assertEqual(actual, expected)

                msg = 'An error occurred while creating a test instance: ' + \
                      '<WSGIRequest: POST ' + \
                      "'/admin/mailcondensers/mailcondenser/1/change/test/'>"
                log_capture.check(
                    ('cyphon.admin', 'ERROR', msg),
                )


问题


面经


文章

微信
公众号

扫码关注公众号