本文整理汇总了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.')
示例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
示例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])
示例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
示例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}
示例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])
示例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()
示例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")
示例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")
示例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
示例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.')
示例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
示例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
示例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
示例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
]