本文整理汇总了Python中django.db.DatabaseError方法的典型用法代码示例。如果您正苦于以下问题:Python db.DatabaseError方法的具体用法?Python db.DatabaseError怎么用?Python db.DatabaseError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db
的用法示例。
在下文中一共展示了db.DatabaseError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_dispatches_for_update
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def _get_dispatches_for_update(filter_kwargs: dict) -> Optional[List['Dispatch']]:
"""Distributed friendly version using ``select for update``."""
dispatches = Dispatch.objects.prefetch_related('message').filter(
**filter_kwargs
).select_for_update(
**GET_DISPATCHES_ARGS[1]
).order_by('-message__time_created')
try:
dispatches = list(dispatches)
except NotSupportedError:
return None
except DatabaseError: # Probably locked. That's fine.
return []
return dispatches
示例2: save
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def save(self, must_create=False):
"""
Save the current session data to the database. If 'must_create' is
True, raise a database error if the saving operation doesn't create a
new entry (as opposed to possibly updating an existing entry).
"""
if self.session_key is None:
return self.create()
data = self._get_session(no_load=must_create)
obj = self.create_model_instance(data)
using = router.db_for_write(self.model, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, force_update=not must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
except DatabaseError:
if not must_create:
raise UpdateError
raise
示例3: get_queryset
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def get_queryset(self):
try:
validity_period = SiteConfiguration.get_solo().confirmation_validity_period
except DatabaseError:
from datetime import timedelta
validity_period = timedelta(weeks=42)
validity_start = timezone.now() - validity_period
return super().get_queryset().annotate(deleted=Case(
When(deleted_on__isnull=True, then=False),
default=True,
output_field=BooleanField()
)).annotate(confirmed=Case(
When(confirmed_on__isnull=True, then=False),
When(confirmed_on__lt=validity_start, then=False),
default=True,
output_field=BooleanField()
)).annotate(checked=Case(
When(checked_on__isnull=True, then=False),
# When(checked_on__lt=validity_start, then=False), # Temporarily disabled.
default=True,
output_field=BooleanField()
)).select_related()
示例4: generic_error_view
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def generic_error_view(error, error_code):
def error_view(request, exception=None):
try:
trope = Trope.objects.order_by('?').first()
except DatabaseError:
return server_error(request)
parameters = {
'error_code': error_code,
'error': error,
}
if trope:
parameters['trope'] = trope
parameters['origin'] = trope.origin
return render(request, 'error.html', parameters, status=error_code)
return error_view
示例5: ready
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def ready(self):
# WARNING: AS THIS IS NOT A FUNCTIONAL PROGRAMMING LANGUAGE,
# OPERATIONS MAY HAVE SIDE EFFECTS.
# DO NOT REMOVE THINKING THE IMPORT IS UNUSED.
# noinspection PyUnresolvedReferences
from . import signals, jinja2 # noqa: F401, imported for side effects
from judge.models import Language, Profile
from django.contrib.auth.models import User
try:
lang = Language.get_default_language()
for user in User.objects.filter(profile=None):
# These poor profileless users
profile = Profile(user=user, language=lang)
profile.save()
except DatabaseError:
pass
示例6: exception_handler
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def exception_handler(exc, context):
"""
自定义异常处理
:param exc: 别的地方抛的异常就会传给exc
:param context: 字典形式。抛出异常的上下文(即抛出异常的出处;即抛出异常的视图)
:return: Response响应对象
"""
# 调用drf框架原生的异常处理方法,把异常和异常出处交给他处理,如果是序列化器异常就直接处理,处理之后就直接返回
response = drf_exception_handler(exc, context)
#如果响应为空表示不是序列化器异常,补充数据库异常
if response is None:
view = context['view']
if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
# 数据库异常
logger.error('[%s] %s' % (view, exc))
response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
示例7: delete_layer_selections
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def delete_layer_selections(layers):
for config_entity in unique(map(lambda layer: layer.config_entity, layers)):
FeatureClassCreator(config_entity).ensure_dynamic_models()
for selection_layer in layers:
try:
# Drop the table
layer_selection_class = get_or_create_layer_selection_class_for_layer(selection_layer, no_table_creation=True)
if layer_selection_class:
if hasattr(layer_selection_class.features, 'through'):
layer_selection_features_class = layer_selection_class.features.through
drop_layer_selection_table(layer_selection_features_class)
drop_layer_selection_table(layer_selection_class)
except DatabaseError, e:
logger.warning(
"Couldn't destroy LayerSelection tables. Maybe the public.layer table no longer exists: %s" % e.message)
示例8: add_or_increment
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def add_or_increment(self, **kwargs):
"""
Handles Metric table updates:
If object does not exist create it, else update the
counter (occurrences) of same instances in the table
:param kwargs: A Dict containing the attributes that identify the obj
:return the object that was created or updated
"""
try:
obj, created = self.get_or_create(**kwargs)
if not created:
obj.occurrences += 1
obj.save()
except DatabaseError as e:
logger.exception(e)
obj = None
# stats shouldn't disrupt website functionality
return obj
示例9: readiness
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def readiness(request):
"""
A successful response from this endpoint goes a step further
and means not only that Django is up and running, but also that
the database can be successfully used from within this service.
"""
try:
# Confirm that we can use the database by making a fast query
# against the Article table. It's not important that the requested
# primary key exists or not, just that the query completes without
# error.
Article.objects.filter(pk=1).exists()
except DatabaseError as e:
reason_tmpl = "service unavailable due to database issue ({!s})"
status, reason = 503, reason_tmpl.format(e)
else:
status, reason = 204, None
return HttpResponse(status=status, reason=reason)
示例10: test_user_info_raises_database_error
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def test_user_info_raises_database_error(django_elasticapm_client, client):
user = User(username="admin", email="admin@example.com")
user.set_password("admin")
user.save()
assert client.login(username="admin", password="admin")
with mock.patch("django.contrib.auth.models.User.is_authenticated") as is_authenticated:
is_authenticated.side_effect = DatabaseError("Test Exception")
with pytest.raises(Exception):
client.get(reverse("elasticapm-raise-exc"))
assert len(django_elasticapm_client.events[ERROR]) == 1
event = django_elasticapm_client.events[ERROR][0]
assert "user" in event["context"]
user_info = event["context"]["user"]
assert user_info == {}
示例11: handle
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def handle(self, *args, **options):
from c3nav.mapdata.models import MapUpdate
logger = logging.getLogger('c3nav')
MapUpdate.objects.create(type='management', geometries_changed=options['include_geometries'])
logger.info('New management update created.')
if options['include_history']:
logger.info('Deleting base history...')
for filename in os.listdir(settings.CACHE_ROOT):
if filename.startswith('history_base_'):
logger.info('Deleting %s...' % filename)
os.remove(os.path.join(settings.CACHE_ROOT, filename))
logger.info('Base history deleted.')
if not settings.HAS_CELERY and not options['no_process']:
print(_('You don\'t have celery installed, so we will run processupdates now...'))
try:
process_map_updates()
except DatabaseError:
logger.error('Didn\'t work, there is already map update processing in progress.')
if not settings.HAS_REAL_CACHE:
print(_('You have no external cache configured, so don\'t forget to restart your c3nav instance!'))
示例12: health
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def health(_request):
if newrelic: # pragma: no cover
newrelic.agent.ignore_transaction()
overall_status = database_status = UNAVAILABLE
try:
cursor = connection.cursor()
cursor.execute("SELECT 1")
cursor.fetchone()
cursor.close()
database_status = OK
except DatabaseError as e:
logger.exception('Insights database is not reachable: %s', e)
database_status = UNAVAILABLE
overall_status = OK if (database_status == OK) else UNAVAILABLE
data = {
'overall_status': overall_status,
'detailed_status': {
'database_connection': database_status,
}
}
return HttpResponse(json.dumps(data), content_type='application/json', status=200 if overall_status == OK else 503)
示例13: save
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
if self.session_key is None:
return self.create()
data = self._get_session(no_load=must_create)
obj = self.create_model_instance(data)
using = router.db_for_write(self.model, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, force_update=not must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
except DatabaseError:
if not must_create:
raise UpdateError
raise
示例14: handle
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def handle(self, *args, **options):
site_app_migration_exists = MigrationRecorder.Migration.objects.filter(app='siteapp', name='0025_auto_20190515_1455')
guardian_migration_exists = MigrationRecorder.Migration.objects.filter(app='guardian', name='0001_initial')
system_settings_exists = MigrationRecorder.Migration.objects.filter(app='system_settings', name='0002_auto_20190808_1947')
# Assume case of existing Database initialized and in state prior to 0.9.0
DB_BEFORE_090 = "True"
try:
if site_app_migration_exists:
DB_BEFORE_090 = "False"
if guardian_migration_exists:
DB_BEFORE_090 = "False"
if system_settings_exists:
DB_BEFORE_090 = "False"
except DatabaseError:
# Treat case of database not initialized as OK to run 0.9.0 migrations
DB_BEFORE_090 = "False"
print(DB_BEFORE_090)
示例15: handle
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import DatabaseError [as 别名]
def handle(self, *args, **options):
try:
role_names = [settings.ROLE_PROJECT_ADMIN, settings.ROLE_ANNOTATOR, settings.ROLE_ANNOTATION_APPROVER]
except KeyError as key_error:
self.stderr.write(self.style.ERROR(f'Missing Key: "{key_error}"'))
for role_name in role_names:
if Role.objects.filter(name=role_name).exists():
continue
role = Role()
role.name = role_name
try:
role.save()
except DatabaseError as db_error:
self.stderr.write(self.style.ERROR(f'Database Error: "{db_error}"'))
else:
self.stdout.write(self.style.SUCCESS(f'Role created successfully "{role_name}"'))