本文整理汇总了Python中django.db.utils.DatabaseError方法的典型用法代码示例。如果您正苦于以下问题:Python utils.DatabaseError方法的具体用法?Python utils.DatabaseError怎么用?Python utils.DatabaseError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.utils
的用法示例。
在下文中一共展示了utils.DatabaseError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _execute_wrapper
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [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])
示例2: validate_thread_sharing
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def validate_thread_sharing(self):
"""
Validates that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `allow_thread_sharing`
property). Raises an exception if the validation fails.
"""
if not (self.allow_thread_sharing
or self._thread_ident == thread.get_ident()):
raise DatabaseError("DatabaseWrapper objects created in a "
"thread can only be used in that same thread. The object "
"with alias '%s' was created in thread id %s and this is "
"thread id %s."
% (self.alias, self._thread_ident, thread.get_ident()))
# ##### Miscellaneous #####
示例3: _nodb_connection
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def _nodb_connection(self):
nodb_connection = super(DatabaseWrapper, self)._nodb_connection
try:
nodb_connection.ensure_connection()
except (DatabaseError, WrappedDatabaseError):
warnings.warn(
"Normally Django will use a connection to the 'postgres' database "
"to avoid running initialization queries against the production "
"database when it's not needed (for example, when running tests). "
"Django was unable to create a connection to the 'postgres' database "
"and will use the default database instead.",
RuntimeWarning
)
settings_dict = self.settings_dict.copy()
settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME']
nodb_connection = self.__class__(
self.settings_dict.copy(),
alias=self.alias,
allow_thread_sharing=False)
return nodb_connection
示例4: supports_stddev
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def supports_stddev(self):
"""Confirm support for STDDEV and related stats functions
SQLite supports STDDEV as an extension package; so
connection.ops.check_expression_support() can't unilaterally
rule out support for STDDEV. We need to manually check
whether the call works.
"""
with self.connection.cursor() as cursor:
cursor.execute('CREATE TABLE STDDEV_TEST (X INT)')
try:
cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST')
has_support = True
except utils.DatabaseError:
has_support = False
cursor.execute('DROP TABLE STDDEV_TEST')
return has_support
示例5: delete_model
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def delete_model(self, model, **kwargs):
from django.contrib.gis.db.models.fields import GeometryField
# Drop spatial metadata (dropping the table does not automatically remove them)
for field in model._meta.local_fields:
if isinstance(field, GeometryField):
self.remove_geometry_metadata(model, field)
# Make sure all geom stuff is gone
for geom_table in self.geometry_tables:
try:
self.execute(
self.sql_discard_geometry_columns % {
"geom_table": geom_table,
"table": self.quote_name(model._meta.db_table),
}
)
except DatabaseError:
pass
super(SpatialiteSchemaEditor, self).delete_model(model, **kwargs)
示例6: validate_thread_sharing
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def validate_thread_sharing(self):
"""
Validate that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `allow_thread_sharing`
property). Raise an exception if the validation fails.
"""
if not (self.allow_thread_sharing or self._thread_ident == _thread.get_ident()):
raise DatabaseError(
"DatabaseWrapper objects created in a "
"thread can only be used in that same thread. The object "
"with alias '%s' was created in thread id %s and this is "
"thread id %s."
% (self.alias, self._thread_ident, _thread.get_ident())
)
# ##### Miscellaneous #####
示例7: supports_stddev
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def supports_stddev(self):
"""
Confirm support for STDDEV and related stats functions.
SQLite supports STDDEV as an extension package; so
connection.ops.check_expression_support() can't unilaterally
rule out support for STDDEV. Manually check whether the call works.
"""
with self.connection.cursor() as cursor:
cursor.execute('CREATE TABLE STDDEV_TEST (X INT)')
try:
cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST')
has_support = True
except utils.DatabaseError:
has_support = False
cursor.execute('DROP TABLE STDDEV_TEST')
return has_support
示例8: _execute_allow_fail_statements
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def _execute_allow_fail_statements(self, cursor, statements, parameters, verbosity, acceptable_ora_err):
"""
Execute statements which are allowed to fail silently if the Oracle
error code given by `acceptable_ora_err` is raised. Return True if the
statements execute without an exception, or False otherwise.
"""
try:
# Statement can fail when acceptable_ora_err is not None
allow_quiet_fail = acceptable_ora_err is not None and len(acceptable_ora_err) > 0
self._execute_statements(cursor, statements, parameters, verbosity, allow_quiet_fail=allow_quiet_fail)
return True
except DatabaseError as err:
description = str(err)
if acceptable_ora_err is None or acceptable_ora_err not in description:
raise
return False
示例9: _nodb_connection
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def _nodb_connection(self):
nodb_connection = super()._nodb_connection
try:
nodb_connection.ensure_connection()
except (Database.DatabaseError, WrappedDatabaseError):
warnings.warn(
"Normally Django will use a connection to the 'postgres' database "
"to avoid running initialization queries against the production "
"database when it's not needed (for example, when running tests). "
"Django was unable to create a connection to the 'postgres' database "
"and will use the default database instead.",
RuntimeWarning
)
settings_dict = self.settings_dict.copy()
settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME']
nodb_connection = self.__class__(
self.settings_dict.copy(),
alias=self.alias,
allow_thread_sharing=False)
return nodb_connection
示例10: _execute_wrapper
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
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])
示例11: test_postgres_trigger_sum_zero
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def test_postgres_trigger_sum_zero(self):
""""
Check the database enforces leg amounts summing to zero
This is enforced by a postgres trigger applied in migration 0005.
Note that this requires the test case extend TransactionTestCase,
as the trigger is only run when changes are committed to the DB
(which the normal TestCase will not do)
"""
account = self.account()
transaction = Transaction.objects.create()
with self.assertRaises(DatabaseError):
Leg.objects.create(transaction=transaction, account=account, amount=100)
with self.assertRaises(DatabaseError), db_transaction.atomic():
# Also ensure we distinguish between currencies
Leg.objects.create(transaction=transaction, account=account, amount=Money(100, "EUR"))
Leg.objects.create(transaction=transaction, account=account, amount=Money(-100, "GBP"))
示例12: process_request
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def process_request(self, request):
connection.set_schema_to_public()
hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0])
try:
domain = get_tenant_domain_model().objects.select_related('tenant').get(domain=hostname_without_port)
request.tenant = domain.tenant
except utils.DatabaseError:
request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
return
except get_tenant_domain_model().DoesNotExist:
if hostname_without_port in ("127.0.0.1", "localhost"):
request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
return
else:
raise Http404
connection.set_tenant(request.tenant)
ContentType.objects.clear_cache()
if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF') and request.tenant.schema_name == get_public_schema_name():
request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
示例13: get_context_data
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
hostname_without_port = remove_www(self.request.get_host().split(':')[0])
try:
Client.objects.get(schema_name='public')
except utils.DatabaseError:
context['need_sync'] = True
context['shared_apps'] = settings.SHARED_APPS
context['tenants_list'] = []
return context
except Client.DoesNotExist:
context['no_public_tenant'] = True
context['hostname'] = hostname_without_port
if Client.objects.count() == 1:
context['only_public_tenant'] = True
context['tenants_list'] = Client.objects.all()
return context
示例14: form_valid
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def form_valid(self, form):
User.objects.all().delete() # clean current users
# generate five random users
users_to_generate = 5
first_names = ["Aiden", "Jackson", "Ethan", "Liam", "Mason", "Noah",
"Lucas", "Jacob", "Jayden", "Jack", "Sophia", "Emma",
"Olivia", "Isabella", "Ava", "Lily", "Zoe", "Chloe",
"Mia", "Madison"]
last_names = ["Smith", "Brown", "Lee", "Wilson", "Martin", "Patel",
"Taylor", "Wong", "Campbell", "Williams"]
while User.objects.count() != users_to_generate:
first_name = choice(first_names)
last_name = choice(last_names)
try:
user = User(username=(first_name+last_name).lower(),
email="%s@%s.com" % (first_name, last_name),
first_name=first_name,
last_name=last_name)
user.save()
except DatabaseError:
pass
return super().form_valid(form)
示例15: initial_signals
# 需要导入模块: from django.db import utils [as 别名]
# 或者: from django.db.utils import DatabaseError [as 别名]
def initial_signals():
from django.db.utils import DatabaseError, IntegrityError
for cmd in ['schemamigration', 'migrate',
'test', 'createsuperuser', 'makemigrations',
'collectstatic', 'compilemessages']:
if cmd in sys.argv:
break
else:
try:
from dbmail.signals import initial_signals as init_signals
init_signals()
except (ImportError, DatabaseError, IntegrityError):
pass
##
# Compatibility section
##