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


Python utils.ProgrammingError方法代碼示例

本文整理匯總了Python中django.db.utils.ProgrammingError方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.ProgrammingError方法的具體用法?Python utils.ProgrammingError怎麽用?Python utils.ProgrammingError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.db.utils的用法示例。


在下文中一共展示了utils.ProgrammingError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: ready

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def ready(self):

        for field_name in self._get_all_workflow_fields():
            try:
                workflows = self.get_model('Workflow').objects.filter(field_name=field_name)
                if workflows.count() == 0:
                    LOGGER.warning("%s field doesn't seem have any workflow defined in database. You should create its workflow" % field_name)
            except (OperationalError, ProgrammingError):
                pass

        from river.config import app_config

        if app_config.INJECT_MODEL_ADMIN:
            for model_class in self._get_all_workflow_classes():
                self._register_hook_inlines(model_class)

        LOGGER.debug('RiverApp is loaded.') 
開發者ID:javrasya,項目名稱:django-river,代碼行數:19,代碼來源:apps.py

示例2: actions_have_consistent_hashes

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def actions_have_consistent_hashes(app_configs, **kwargs):
    errors = []
    try:
        Action = apps.get_model("recipes", "Action")
        actions = list(Action.objects.filter(implementation__isnull=False))
    except (ProgrammingError, OperationalError, ImproperlyConfigured) as e:
        errors.append(Info(f"Could not retrieve actions: {e}", id=INFO_COULD_NOT_RETRIEVE_ACTIONS))
    else:
        for action in actions:
            if action.compute_implementation_hash() != action.implementation_hash:
                msg = "Action '{action}' (id={action.id}) has a mismatched hash".format(
                    action=action
                )
                errors.append(Error(msg, id=ERROR_MISMATCHED_ACTION_HASH))

    return errors 
開發者ID:mozilla,項目名稱:normandy,代碼行數:18,代碼來源:checks.py

示例3: _execute_wrapper

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [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

示例4: spatial_version

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def spatial_version(self):
        """Determine the version of the PostGIS library."""
        # Trying to get the PostGIS version because the function
        # signatures will depend on the version used.  The cost
        # here is a database query to determine the version, which
        # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple
        # comprising user-supplied values for the major, minor, and
        # subminor revision of PostGIS.
        if hasattr(settings, 'POSTGIS_VERSION'):
            version = settings.POSTGIS_VERSION
        else:
            try:
                vtup = self.postgis_version_tuple()
            except ProgrammingError:
                raise ImproperlyConfigured(
                    'Cannot determine PostGIS version for database "%s". '
                    'GeoDjango requires at least PostGIS version 1.5. '
                    'Was the database created from a spatial database '
                    'template?' % self.connection.settings_dict['NAME']
                )
            version = vtup[1:]
        return version 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:24,代碼來源:operations.py

示例5: test_sql_psycopg2_string_composition

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def test_sql_psycopg2_string_composition(sentry_init, capture_events, query):
    sentry_init(
        integrations=[DjangoIntegration()],
        send_default_pii=True,
        _experiments={"record_sql_params": True},
    )
    from django.db import connections

    if "postgres" not in connections:
        pytest.skip("postgres tests disabled")

    import psycopg2.sql

    sql = connections["postgres"].cursor()

    events = capture_events()
    with pytest.raises(ProgrammingError):
        sql.execute(query(psycopg2.sql), {"my_param": 10})

    capture_message("HI")

    (event,) = events
    crumb = event["breadcrumbs"][-1]
    assert crumb["message"] == ('SELECT %(my_param)s FROM "foobar"')
    assert crumb["data"]["db.params"] == {"my_param": 10} 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:27,代碼來源:test_basic.py

示例6: _execute_wrapper

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [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

示例7: clone_schema

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def clone_schema(self, base_schema_name, new_schema_name, set_connection=True):
        """
        Creates a new schema `new_schema_name` as a clone of an existing schema
        `old_schema_name`.
        """
        if set_connection:
            connection.set_schema_to_public()
        cursor = connection.cursor()

        # check if the clone_schema function already exists in the db
        try:
            cursor.execute("SELECT 'clone_schema'::regproc")
        except ProgrammingError:
            self._create_clone_schema_function()
            transaction.commit()

        if schema_exists(new_schema_name):
            raise ValidationError("New schema name already exists")

        sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, true, false)'
        cursor.execute(
            sql,
            {'base_schema': base_schema_name, 'new_schema': new_schema_name}
        )
        cursor.close() 
開發者ID:django-tenants,項目名稱:django-tenants,代碼行數:27,代碼來源:clone.py

示例8: generate_part_thumbnails

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def generate_part_thumbnails(self):
        from .models import Part

        print("InvenTree: Checking Part image thumbnails")

        try:
            for part in Part.objects.all():
                if part.image:
                    url = part.image.thumbnail.name
                    loc = os.path.join(settings.MEDIA_ROOT, url)
                    
                    if not os.path.exists(loc):
                        print("InvenTree: Generating thumbnail for Part '{p}'".format(p=part.name))
                        try:
                            part.image.render_variations(replace=False)
                        except FileNotFoundError:
                            print("Image file missing")
                            part.image = None
                            part.save()
        except (OperationalError, ProgrammingError):
            print("Could not generate Part thumbnails") 
開發者ID:inventree,項目名稱:InvenTree,代碼行數:23,代碼來源:apps.py

示例9: generate_company_thumbs

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def generate_company_thumbs(self):

        from .models import Company

        print("InvenTree: Checking Company image thumbnails")

        try:
            for company in Company.objects.all():
                if company.image:
                    url = company.image.thumbnail.name
                    loc = os.path.join(settings.MEDIA_ROOT, url)

                    if not os.path.exists(loc):
                        print("InvenTree: Generating thumbnail for Company '{c}'".format(c=company.name))
                        try:
                            company.image.render_variations(replace=False)
                        except FileNotFoundError:
                            print("Image file missing")
                            company.image = None
                            company.save()
        except (OperationalError, ProgrammingError):
            print("Could not generate Company thumbnails") 
開發者ID:inventree,項目名稱:InvenTree,代碼行數:24,代碼來源:apps.py

示例10: setUp

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def setUp(self):
        # Create a dummy model which extends the mixin. A RuntimeWarning will
        # occur if the model is registered twice
        if not hasattr(self, 'model'):
            self.model = ModelBase(
                '__TestModel__' +
                self.mixin.__name__, (self.mixin,),
                {'__module__': self.mixin.__module__}
            )

        # Create the schema for our test model. If the table already exists,
        # will pass
        try:
            with connection.schema_editor() as schema_editor:
                schema_editor.create_model(self.model)
            super(AbstractModelMixinTestCase, self).setUpClass()
        except ProgrammingError:
            pass 
開發者ID:Disfactory,項目名稱:Disfactory,代碼行數:20,代碼來源:test_mixins.py

示例11: handle

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def handle(self, *args, **options):
        super_username = os.getenv('KOBO_SUPERUSER_USERNAME', 'kobo')
        if User.objects.filter(username=super_username).count() > 0:
            self.stdout.write('User already exists.')
            sys.exit()

        try:
            User.objects.create_superuser(
                os.getenv('KOBO_SUPERUSER_USERNAME', 'kobo'),
                os.getenv('KOBO_SUPERUSER_EMAIL', 'kobo@example.com'),
                os.getenv('KOBO_SUPERUSER_PASSWORD', 'kobo'))
        except ProgrammingError:  # Signals fail when `kc` database
            pass                  # doesn't exist yet.
        except Exception as e:
            self.stdout.write('Superuser could not be created.\n'
                              'Error: {}'.format(str(e)))

        if User.objects.filter(username=super_username).count() > 0:
            self.stdout.write('Superuser successfully created.') 
開發者ID:kobotoolbox,項目名稱:kpi,代碼行數:21,代碼來源:create_kobo_superuser.py

示例12: check_schema_names

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def check_schema_names(app_configs, **kwargs):
    errors = []
    static_names = set(settings.TENANTS.keys())
    clone_reference = get_clone_reference()
    if clone_reference:
        static_names.add(clone_reference)
    try:
        dynamic_names = set(get_tenant_model().objects.values_list("schema_name", flat=True))
    except ProgrammingError:
        # This happens on the first run of migrate, with empty database.
        # It can also happen when the tenant model contains unapplied migrations that break.
        dynamic_names = set()
    intersection = static_names & dynamic_names
    if intersection:
        errors.append(
            checks.Critical(
                "Name clash found between static and dynamic tenants: %s" % intersection, id="pgschemas.W004",
            )
        )
    return errors 
開發者ID:lorinkoz,項目名稱:django-pgschemas,代碼行數:22,代碼來源:checks.py

示例13: get_schemas_from_options

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def get_schemas_from_options(self, **options):
        skip_schema_creation = options.get("skip_schema_creation", False)
        try:
            schemas = self._get_schemas_from_options(**options)
        except ProgrammingError:
            # This happens with unmigrated database.
            # It can also happen when the tenant model contains unapplied migrations that break.
            raise CommandError(
                "Error while attempting to retrieve dynamic schemas. "
                "Perhaps you need to migrate the 'public' schema first?"
            )
        if self.specific_schemas is not None:
            schemas = [x for x in schemas if x in self.specific_schemas]
            if not schemas:
                raise CommandError("This command can only run in %s" % self.specific_schemas)
        if not skip_schema_creation:
            for schema in schemas:
                create_schema(schema, check_if_exists=True, sync_schema=False, verbosity=0)
        return schemas 
開發者ID:lorinkoz,項目名稱:django-pgschemas,代碼行數:21,代碼來源:__init__.py

示例14: current

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def current(self):
        """Return the current value of this sequence, or `None`.

        :return: The sequence value, or None if there is no current value for
            the sequence in the database session or if the sequence does not
            exist.
        :rtype: int / None
        """
        try:
            with transaction.atomic():
                with connection.cursor() as cursor:
                    cursor.execute("SELECT currval(%s)", [self.name])
                    return cursor.fetchone()[0]
        except utils.OperationalError as error:
            if is_postgres_error(error, OBJECT_NOT_IN_PREREQUISITE_STATE):
                # There is no current value for the sequence in this session.
                return None
            else:
                raise
        except utils.ProgrammingError as error:
            if is_postgres_error(error, UNDEFINED_TABLE):
                # The sequence does not exist, hence has no current value.
                return None
            else:
                raise 
開發者ID:maas,項目名稱:maas,代碼行數:27,代碼來源:sequence.py

示例15: execute_sql

# 需要導入模塊: from django.db import utils [as 別名]
# 或者: from django.db.utils import ProgrammingError [as 別名]
def execute_sql(self, return_id=False):
        # execute all the generate queries
        with self.connection.cursor() as cursor:
            rows = []
            for sql, params in self.as_sql(return_id):
                cursor.execute(sql, params)
                try:
                    rows.extend(cursor.fetchall())
                except ProgrammingError:
                    pass

        # create a mapping between column names and column value
        return [
            {
                column.name: row[column_index]
                for column_index, column in enumerate(cursor.description)
                if row
            }
            for row in rows
        ] 
開發者ID:SectorLabs,項目名稱:django-postgres-extra,代碼行數:22,代碼來源:compiler.py


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