當前位置: 首頁>>代碼示例>>Python>>正文


Python db.OperationalError方法代碼示例

本文整理匯總了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 
開發者ID:project-koku,項目名稱:koku,代碼行數:19,代碼來源:database.py

示例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 
開發者ID:project-koku,項目名稱:koku,代碼行數:26,代碼來源:storage.py

示例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 
開發者ID:project-koku,項目名稱:koku,代碼行數:22,代碼來源:storage.py

示例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) 
開發者ID:project-koku,項目名稱:koku,代碼行數:25,代碼來源:test_kafka_listener.py

示例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)) 
開發者ID:project-koku,項目名稱:koku,代碼行數:19,代碼來源:report_processor.py

示例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 
開發者ID:aclowes,項目名稱:yawn,代碼行數:22,代碼來源:database.py

示例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() 
開發者ID:Cadasta,項目名稱:cadasta-platform,代碼行數:19,代碼來源:test_consumer.py

示例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() 
開發者ID:Cadasta,項目名稱:cadasta-platform,代碼行數:24,代碼來源:consumer.py

示例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 
開發者ID:evernote,項目名稱:zing,代碼行數:23,代碼來源:checks.py

示例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 
開發者ID:evernote,項目名稱:zing,代碼行數:22,代碼來源:checks.py

示例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 
開發者ID:opentaps,項目名稱:opentaps_seas,代碼行數:27,代碼來源:point.py

示例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') 
開發者ID:opentaps,項目名稱:opentaps_seas,代碼行數:18,代碼來源:models.py

示例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 
開發者ID:edx,項目名稱:edx-analytics-data-api,代碼行數:19,代碼來源:problems.py

示例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 
開發者ID:openlegaldata,項目名稱:oldp,代碼行數:23,代碼來源:reference_processor.py

示例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 
開發者ID:openlegaldata,項目名稱:oldp,代碼行數:24,代碼來源:case_processor.py


注:本文中的django.db.OperationalError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。