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


Python utils.DatabaseError方法代碼示例

本文整理匯總了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]) 
開發者ID:LuciferJack,項目名稱:python-mysql-pool,代碼行數:24,代碼來源:base.py

示例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 ##### 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:18,代碼來源:base.py

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

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

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

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

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

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

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

示例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]) 
開發者ID:CastagnaIT,項目名稱:plugin.video.netflix,代碼行數:24,代碼來源:base.py

示例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")) 
開發者ID:adamcharnock,項目名稱:django-hordak,代碼行數:21,代碼來源:test_core.py

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

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

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

示例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
## 
開發者ID:LPgenerator,項目名稱:django-db-mailer,代碼行數:22,代碼來源:__init__.py


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