本文整理汇总了Python中django.db.OperationalError方法的典型用法代码示例。如果您正苦于以下问题:Python db.OperationalError方法的具体用法?Python db.OperationalError怎么用?Python db.OperationalError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db
的用法示例。
在下文中一共展示了db.OperationalError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_migrations
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def check_migrations():
"""
Check the status of database migrations.
The koku API server is responsible for running all database migrations. This method
will return the state of the database and whether or not all migrations have been completed.
Hat tip to the Stack Overflow contributor: https://stackoverflow.com/a/31847406
Returns:
Boolean - True if database is available and migrations have completed. False otherwise.
"""
try:
connection = connections[DEFAULT_DB_ALIAS]
connection.prepare_database()
executor = MigrationExecutor(connection)
targets = executor.loader.graph.leaf_nodes()
return not executor.migration_plan(targets)
except OperationalError:
return False
示例2: destroy_source_event
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def destroy_source_event(source_id):
"""
Destroy a Sources database object.
Args:
source_id (Integer) - Platform-Sources identifier
Returns:
None
"""
koku_uuid = None
try:
source = Sources.objects.get(source_id=source_id)
koku_uuid = source.koku_uuid
source.delete()
LOG.info(f"source.storage.destroy_source_event destroyed Source ID: {source_id}")
except Sources.DoesNotExist:
LOG.debug("Source ID: %s already removed.", str(source_id))
except (InterfaceError, OperationalError) as error:
LOG.error(f"source.storage.destroy_provider_event {type(error).__name__}: {error}")
raise error
return koku_uuid
示例3: is_known_source
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def is_known_source(source_id):
"""
Check if source exists in database.
Args:
source_id (Integer) - Platform-Sources identifier
Returns:
source_exists (Boolean) - True if source is known
"""
try:
Sources.objects.get(source_id=source_id)
source_exists = True
except Sources.DoesNotExist:
source_exists = False
except (InterfaceError, OperationalError) as error:
LOG.error(f"Accessing Sources resulting in {type(error).__name__}: {error}")
raise error
return source_exists
示例4: test_process_synchronize_sources_msg_db_error
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def test_process_synchronize_sources_msg_db_error(self, mock_process_message):
"""Test processing synchronize messages with database errors."""
provider = Sources.objects.create(**self.aws_source)
provider.save()
future_mock = asyncio.Future()
future_mock.set_result("test result")
test_queue = queue.PriorityQueue()
test_matrix = [
{"test_value": {"operation": "update", "provider": provider}, "side_effect": InterfaceError},
{"test_value": {"operation": "update", "provider": provider}, "side_effect": OperationalError},
]
for i, test in enumerate(test_matrix):
mock_process_message.side_effect = test.get("side_effect")
with patch("sources.kafka_listener.connection.close") as close_mock:
with patch.object(Config, "RETRY_SECONDS", 0):
process_synchronize_sources_msg((i, test["test_value"]), test_queue)
close_mock.assert_called()
for i in range(2):
priority, _ = test_queue.get_nowait()
self.assertEqual(priority, i)
示例5: process
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def process(self):
"""
Process the current cost usage report.
Args:
None
Returns:
(List) List of filenames downloaded.
"""
try:
return self._processor.process()
except (InterfaceError, DjangoInterfaceError, OperationalError) as err:
raise ReportProcessorDBError(str(err))
except Exception as err:
raise ReportProcessorError(str(err))
示例6: close_on_exception
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def close_on_exception(func):
"""
A wrapper to close the database connection if a DB error occurs,
so that it will get re-opened on the next use.
Squashes the exception and logs it.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except OperationalError:
logger.error('Database error, closing connection', exc_info=True)
db.connection.close()
assert db.connection.closed_in_transaction is False, \
'Could not close connection, probably because this wrapper ' \
'was used inside an transaction.atomic() block.'
return wrapper
示例7: test_process_task_handles_failed_db
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def test_process_task_handles_failed_db(
self, close_old_connections, handle_task, logger):
"""
Ensure that process_task() gracefully handles closed DB connections
"""
for err in (InterfaceError, OperationalError):
handle_task.side_effect = err('Broken DB')
body = MagicMock()
msg = MagicMock()
# First time will fail, will log error, and not ack message
self.mock_worker.process_task(body, msg)
assert not msg.ack.called
assert logger.exception.calls[0][0]
assert close_old_connections.called
close_old_connections.reset_mock()
示例8: process_task
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def process_task(self, body, message):
logger.info('Processing message: %r', message)
try:
self._handle_task(body, message)
except (OperationalError, InterfaceError):
# Lost DB connection, close DB and don't ack() msg.
# A new DB connection will be re-opened next time we
# try to access the DB. Msg will be re-processed
# after SQS visibility timeout passes.
logger.exception("DB connection lost. Cleaning up connections")
return close_old_connections()
except: # NOQA
logger.exception("Failed to process message: %r", message)
logger.info("ACKing message %r", message)
if self.connection.as_uri().lower().startswith('sqs://'):
# HACK: Can't seem to get message.ack() to work for SQS
# backend. Without this hack, messages will keep
# re-appearing after the visibility_timeout expires.
# See https://github.com/celery/kombu/issues/758
return self._sqs_ack(message)
return message.ack()
示例9: check_users
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def check_users(app_configs=None, **kwargs):
from django.contrib.auth import get_user_model
errors = []
User = get_user_model()
try:
admin_user = User.objects.get(username="admin")
except (User.DoesNotExist, OperationalError, ProgrammingError):
pass
else:
if admin_user.check_password("admin"):
errors.append(
checks.Warning(
_("The default 'admin' user still has a password set to 'admin'."),
hint=_("Remove the 'admin' user or change its password."),
id="pootle.W016",
)
)
return errors
示例10: check_revision
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def check_revision(app_configs=None, **kwargs):
from pootle.core.models import Revision
from pootle_store.models import Unit
errors = []
revision = Revision.get()
try:
max_revision = Unit.max_revision()
except (OperationalError, ProgrammingError):
return errors
if revision is None or revision < max_revision:
errors.append(
checks.Critical(
_("Revision is missing or has an incorrect value."),
hint=_("Run `revision --restore` to reset the revision counter."),
id="pootle.C016",
)
)
return errors
示例11: get_context_data
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def get_context_data(self, **kwargs):
context = super(PointDetailView, self).get_context_data(**kwargs)
context['grafana_url'] = settings.GRAFANA_BASE_URL + "/d/"
# add the parent Site (optional)
try:
context['site'] = SiteView.objects.get(object_id=context['object'].site_id)
except SiteView.DoesNotExist:
pass
# add the parent Equipment (optional)
try:
context['equipment'] = EquipmentView.objects.get(object_id=context['object'].equipment_id)
except EquipmentView.DoesNotExist:
pass
if context['object']:
charts = []
try:
charts = utils.charts_for_points([context['object']])
except OperationalError:
logging.warning('Crate database unavailable')
context['charts'] = charts
return context
示例12: delete_tags_from_crate_entity
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def delete_tags_from_crate_entity(row):
# we only sync for entity linked to a topic
if not row.topic:
return
try:
with connections['crate'].cursor() as c:
# make sure the topic is in CrateDB
sql = """DELETE {0} WHERE topic = %s;""".format("topic")
try:
c.execute(sql, [row.topic])
except Exception:
# ignore if the entity did not exist
pass
except OperationalError:
logging.warning('Crate database unavailable')
示例13: get_queryset
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def get_queryset(self):
"""Select all the answer distribution response having to do with this usage of the problem."""
problem_id = self.kwargs.get('problem_id')
try:
queryset = list(ProblemResponseAnswerDistribution.objects.filter(module_id=problem_id).order_by('part_id'))
except OperationalError:
self.serializer_class = ConsolidatedFirstLastAnswerDistributionSerializer
queryset = list(ProblemFirstLastResponseAnswerDistribution.objects.filter(
module_id=problem_id).order_by('part_id'))
consolidated_rows = []
for _, part in groupby(queryset, lambda x: x.part_id):
consolidated_rows += self.consolidate_answers(list(part))
return consolidated_rows
示例14: process_content
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def process_content(self):
for content in self.pre_processed_content: # type: Reference
try:
# First save (some processing steps require ids)
content.full_clean() # Validate model
content.save()
self.call_processing_steps(content)
# Save again
content.save()
logger.debug('Completed: %s' % content)
self.doc_counter += 1
self.processed_content.append(content)
except (ValidationError, DataError, OperationalError, IntegrityError, ProcessingError) as e:
logger.error('Cannot process: %s; %s' % (content, e))
self.processing_errors.append(e)
self.doc_failed_counter += 1
示例15: process_content_item
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import OperationalError [as 别名]
def process_content_item(self, content: Case) -> Case:
try:
# First save (some processing steps require ids)
# content.full_clean() # Validate model
content.save()
self.call_processing_steps(content)
# Save again
content.save()
logger.debug('Completed: %s' % content)
self.doc_counter += 1
self.processed_content.append(content)
except (ValidationError, DataError, OperationalError, IntegrityError, ProcessingError) as e:
logger.error('Cannot process case: %s; %s' % (content, e))
self.processing_errors.append(e)
self.doc_failed_counter += 1
return content