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


Python db.DatabaseError方法代碼示例

本文整理匯總了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 
開發者ID:idlesign,項目名稱:django-sitemessage,代碼行數:23,代碼來源:models.py

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

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

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

示例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 
開發者ID:DMOJ,項目名稱:online-judge,代碼行數:20,代碼來源:apps.py

示例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 
開發者ID:xuchaoa,項目名稱:CTF_AWD_Platform,代碼行數:20,代碼來源:exceptions.py

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

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

示例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) 
開發者ID:mdn,項目名稱:developer-portal,代碼行數:20,代碼來源:views.py

示例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 == {} 
開發者ID:elastic,項目名稱:apm-agent-python,代碼行數:19,代碼來源:django_tests.py

示例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!')) 
開發者ID:c3nav,項目名稱:c3nav,代碼行數:27,代碼來源:clearmapcache.py

示例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) 
開發者ID:edx,項目名稱:edx-analytics-dashboard,代碼行數:27,代碼來源:views.py

示例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 
開發者ID:bpgc-cte,項目名稱:python2017,代碼行數:25,代碼來源:db.py

示例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) 
開發者ID:GovReady,項目名稱:govready-q,代碼行數:22,代碼來源:db_before_090.py

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


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