本文整理汇总了Python中django.db.utils.IntegrityError方法的典型用法代码示例。如果您正苦于以下问题:Python utils.IntegrityError方法的具体用法?Python utils.IntegrityError怎么用?Python utils.IntegrityError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.utils
的用法示例。
在下文中一共展示了utils.IntegrityError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: extract_context
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def extract_context(html, url):
soup = BeautifulSoup(html)
# Insert into Content (under this domain)
texts = soup.findAll(text=True)
try:
Content.objects.create(
url=url,
title=soup.title.string,
summary=helpers.strip_tags(" \n".join(filter(visible, texts)))[:4000],
last_crawled_at=datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
)
except IntegrityError:
println('%s - already existed in Content' % url)
soup.prettify()
return [str(anchor['href'])
for anchor in soup.findAll('a', attrs={'href': re.compile("^http://")}) if anchor['href']]
示例2: test_create_violates_unique
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def test_create_violates_unique(self, ):
'''Test CourseDailyMetrics unique constraints
First create a model instance, then try creating with the same
date_for and course_id. It should raise IntegrityError
'''
rec = dict(
site=self.site,
date_for=datetime.date(2018, 2, 2),
course_id='course-v1:SomeOrg+ABC01+2121',
enrollment_count=11,
active_learners_today=1,
average_progress=0.5,
average_days_to_complete=5,
num_learners_completed=10
)
metrics = CourseDailyMetrics.objects.create(**rec)
with pytest.raises(IntegrityError) as e_info:
metrics = CourseDailyMetrics.objects.create(**rec)
assert e_info.value.message.startswith('UNIQUE constraint failed')
示例3: form_valid
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def form_valid(self, form):
base, created = BaseKeyword.objects.get_or_create(term=form.cleaned_data['term'])
keyword = Keyword()
keyword.base = base
keyword.project = self.request.project
try:
keyword.save()
except IntegrityError:
# The unique_together constraint on Keyword model failed
# TODO: Handle a more specific error, IntegrityError could be raised by things other than duplicate too
messages.add_message(
message=_('You already have that keyword for this project, so we did not add it again.'),
level=messages.INFO,
request=self.request,
extra_tags='module-level'
)
return HttpResponseRedirect(self.get_success_url())
示例4: union
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def union(p, q):
for url in p:
parsed = urlparse(str(url))
if parsed.netloc and parsed.netloc != 'www.webhostingtalk.com':
url = 'http://%s/' % parsed.netloc
if parsed.netloc and url not in q:
print url
if parsed.netloc != 'www.webhostingtalk.com':
# Insert into Site
try:
Website.objects.create(
url=url,
name=parsed.netloc,
last_crawled_at=datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
)
except IntegrityError:
println('%s - already existed in Site' % url)
else:
# We want to deep crawl webhosting talk
q.append(url)
示例5: generic_api_view
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def generic_api_view(view_func):
def wrapped_view(request, *args, **kwargs):
try:
return view_func(request, *args, **kwargs)
except PermissionDenied as e:
return generic_error_json('Permission Denied', e, status=403)
except IntegrityError as e:
return generic_error_json('Integrity Error', e)
except ValidationError as e:
return generic_error_json(
'Validation Error',
e,
pretty_exception='See message_dict and/or messages for details',
additional_keys=('message_dict', 'messages', 'code', 'params'),
)
except (AttributeError, KeyError, FieldError, ValueError) as e:
return generic_error_json('Malformed Parameters', e)
except FieldDoesNotExist as e:
return generic_error_json('Field does not exist', e)
except ObjectDoesNotExist as e:
return generic_error_json('Foreign Key relation could not be found', e)
return wrapped_view
示例6: test_FormGroups
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def test_FormGroups(self):
groupName = "admins_test"
u1 = Unit.objects.get(label="CMPT")
u2 = Unit.objects.get(label="ENSC")
# Test saving one form group
fg = FormGroup(name=groupName, unit=u1)
fg.save()
self.assertEqual(fg.name, groupName)
# now try adding another fromgroup in the same name with the same unit
# should throw an db integrity exception
fg2 = FormGroup(name=groupName, unit=u1)
with self.assertRaises(IntegrityError):
with django.db.transaction.atomic():
fg2.save()
# now add a formgroup with the same name into a different unit
fg2 = FormGroup(name=groupName, unit=u2)
fg2.save()
self.assertEqual(fg2.name, groupName)
self.assertEqual(fg2.unit, u2)
# add some people to the fg
p1 = Person.objects.get(userid="ggbaker")
p2 = Person.objects.get(userid="dzhao")
FormGroupMember(person=p1, formgroup=fg).save()
FormGroupMember(person=p2, formgroup=fg).save()
self.assertEqual(len(fg.members.all()), 2)
示例7: add_mapbox_layer
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def add_mapbox_layer(
self, layer_name=False, mapbox_json_path=False, layer_icon="fa fa-globe", is_basemap=False,
):
if layer_name is not False and mapbox_json_path is not False:
with open(mapbox_json_path) as data_file:
data = json.load(data_file)
with transaction.atomic():
for layer in data["layers"]:
if "source" in layer:
layer["source"] = layer["source"] + "-" + layer_name
for source_name, source_dict in data["sources"].items():
map_source = models.MapSource.objects.get_or_create(name=source_name + "-" + layer_name, source=source_dict)
map_layer = models.MapLayer(
name=layer_name, layerdefinitions=data["layers"], isoverlay=(not is_basemap), icon=layer_icon
)
try:
map_layer.save()
except IntegrityError as e:
print("Cannot save layer: {0} already exists".format(layer_name))
示例8: _execute_wrapper
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
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])
示例9: _commit
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
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.
示例10: executemany
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
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
示例11: _test_uniqueness_ignores_deleted
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def _test_uniqueness_ignores_deleted(
self, factory: Type[DjangoModelFactory], **kwargs
):
"""Ensure uniqueness doesn't take deleted instances into account.
Parameters
----------
factory: Type[DjangoModelFactory]
The factory to use to create/delete some objects
kwargs:
Arguments to pass to the given `factory`.
"""
obj1 = factory(**kwargs)
# force a soft deletion (useful for through models configured with ``HARD_DELETE``)
obj1.delete(force_policy=SOFT_DELETE_CASCADE)
self.assertIsSoftDeleted(obj1)
# we can create it again
factory(**kwargs)
# when exists non-deleted, cannot create another one
with self.assertRaises(IntegrityError):
factory(**kwargs)
示例12: test_models_video_fields_lti_id_unique
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def test_models_video_fields_lti_id_unique(self):
"""Videos should be unique for a given duo lti_id/playlist (see LTI specification)."""
video = VideoFactory()
# A video with a different lti_id and the same playlist can still be created
VideoFactory(playlist=video.playlist)
# A video for a different playlist and the same lti_id can still be created
VideoFactory(lti_id=video.lti_id)
# Trying to create a video with the same duo lti_id/playlist should raise a
# database error
with self.assertRaises(IntegrityError):
with transaction.atomic():
VideoFactory(lti_id=video.lti_id, playlist=video.playlist)
# Soft deleted videos should not count for unicity
video.delete(force_policy=SOFT_DELETE_CASCADE)
VideoFactory(lti_id=video.lti_id, playlist=video.playlist)
示例13: test_models_playlist_fields_lti_id_unique
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def test_models_playlist_fields_lti_id_unique(self):
"""Playlists should be unique for a given duo: lti_id/playlist."""
playlist = PlaylistFactory()
# A playlist with a different lti_id and the same consumer site can still be created
PlaylistFactory(consumer_site=playlist.consumer_site)
# A playlist for a different consumer site and the same lti_id can still be created
PlaylistFactory(lti_id=playlist.lti_id)
# Trying to create a playlist with the same duo lti_id/consumer site should raise a
# database error
with self.assertRaises(IntegrityError):
with transaction.atomic():
PlaylistFactory(
lti_id=playlist.lti_id, consumer_site=playlist.consumer_site
)
# Soft deleted playlists should not count for unicity
playlist.delete(force_policy=SOFT_DELETE_CASCADE)
PlaylistFactory(lti_id=playlist.lti_id, consumer_site=playlist.consumer_site)
示例14: create_customer
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def create_customer(account):
"""Create a customer.
Args:
account (str): The account identifier
Returns:
(Customer) The created customer
"""
try:
with transaction.atomic():
schema_name = create_schema_name(account)
customer = Customer(account_id=account, schema_name=schema_name)
customer.save()
tenant = Tenant(schema_name=schema_name)
tenant.save()
UNIQUE_ACCOUNT_COUNTER.inc()
LOG.info("Created new customer from account_id %s.", account)
except IntegrityError:
customer = Customer.objects.filter(account_id=account).get()
return customer
示例15: create_user
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import IntegrityError [as 别名]
def create_user(username, email, customer, request):
"""Create a user for a customer.
Args:
username (str): The username
email (str): The email for the user
customer (Customer): The customer the user is associated with
request (object): The incoming request
Returns:
(User) The created user
"""
new_user = None
try:
with transaction.atomic():
user_data = {"username": username, "email": email}
context = {"request": request, "customer": customer}
serializer = UserSerializer(data=user_data, context=context)
if serializer.is_valid(raise_exception=True):
new_user = serializer.save()
UNIQUE_USER_COUNTER.labels(account=customer.account_id, user=username).inc()
LOG.info("Created new user %s for customer(account_id %s).", username, customer.account_id)
except (IntegrityError, ValidationError):
new_user = User.objects.get(username=username)
return new_user