我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用django.db.utils.IntegrityError()。
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.
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
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()
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)
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()
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()
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])
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
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)
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])
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()
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()
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])) )
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()
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
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)
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)
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), )
def test_integrity_error(self): """ Tests the configuration test tool when an IntegrityError is raised. """ self.page.config_test_value = json.dumps({'text': 'test'}) 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/datacondensers/datacondenser/1/change/test/'>" log_capture.check( ('cyphon.admin', 'ERROR', msg), )
def test_integrity_error(self): """ Tests the configuration test tool when an IntegrityError is raised. """ 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/logcondensers/logcondenser/1/change/test/'>" log_capture.check( ('cyphon.admin', 'ERROR', msg), )
def handle(self, *args, **options): with open(options['path'], 'r') as input_data: data = csv.reader(input_data, delimiter='\t') for row in data: name, address, phone, lat, lng = row logger.info(row) try: hospital = Hospital( hospital_id=shortuuid.uuid(), name=name, address=address, phone=phone, opening_hours='', lng=lng, lat=lat ) hospital.save(using=options['database']) except IntegrityError: print('data have already been imported') break
def handle(self, *args, **options): with open('dengue_linebot/data/tainan_minarea.json') as file: data = json.load(file) for area in data['features']: try: minarea = MinArea( area_id=area['properties']['VILLAGEID'], area_sn=area['properties']['VILLAGESN'], area_name=area['properties']['VILLAGENAM'], district_name=area['properties']['TOWNNAME'], area=GEOSGeometry(json.dumps(area['geometry'])) ) minarea.save() except IntegrityError: self.stderr.write('data have already been imported') break self.stdout.write('Successfully imported')
def mig_users(self, cnx, cursor): query = 'SELECT * FROM user;' cursor.execute(query) o2n_map = {} for user in cursor: new_user = Poster(username=user['username'], email=user['email'], password=user['token'], backend='ISS.auth.backends.vB5_%s' % user['scheme']) try: new_user.save() o2n_map[user['userid']] = new_user.pk except IntegrityError: o2n_map[user['userid']] = Poster.objects.get( username=user['username']).pk return o2n_map
def mig_thanks(self, cnx, cursor, user_pk_map, post_pk_map): cursor.execute(""" SELECT contentid, userid, receiveduserid FROM dbtech_thanks_entry WHERE varname='thanks' GROUP BY contentid, userid, receiveduserid """) for thanks in cursor: try: post_id = post_pk_map[thanks['contentid']] except KeyError: print ('Error migrating thanks: post %d was not found' % thanks['contentid']) else: new_thanks = Thanks( thanker_id=user_pk_map[thanks['userid']], thankee_id=user_pk_map[thanks['receiveduserid']], post_id=post_id) try: new_thanks.save() except IntegrityError, e: import pdb; pdb.set_trace() return
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 # Oracle doesn't support releasing savepoints. But we fake them when query # logging is enabled to keep query counts consistent with other backends.