本文整理匯總了Python中django.db.ProgrammingError方法的典型用法代碼示例。如果您正苦於以下問題:Python db.ProgrammingError方法的具體用法?Python db.ProgrammingError怎麽用?Python db.ProgrammingError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.db
的用法示例。
在下文中一共展示了db.ProgrammingError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_sql
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def get_sql(self, app_label, migration_name):
logger.info(
"Calling sqlmigrate command {} {}".format(app_label, migration_name)
)
dev_null = open(os.devnull, "w")
try:
sql_statement = call_command(
"sqlmigrate",
app_label,
migration_name,
database=self.database,
stdout=dev_null,
)
except (ValueError, ProgrammingError):
logger.warning(
(
"Error while executing sqlmigrate on (%s, %s). "
"Continuing execution with empty SQL."
),
app_label,
migration_name,
)
sql_statement = ""
return sql_statement.splitlines()
示例2: process_exception
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def process_exception(self, request, exception):
# Ignore exception catching if debug mode is on
if settings.DEBUG:
return
# Lets Django handling 404
if isinstance(exception, Http404):
return
template = None
if isinstance(exception, ProgrammingError):
template = "errors/programming_error.html"
elif isinstance(exception, ImportError):
template = "errors/import_error.html"
if template:
return ServerError(request, template_name=template)
示例3: get_config
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def get_config(key: str):
from palanaeum.models import ConfigEntry
value = cache.get(key)
if value is not None:
return _deserialize_value(key, value)
try:
value = ConfigEntry.objects.get(key=key).value
cache.set(key, value)
except ConfigEntry.DoesNotExist:
value = CONFIG_ENTRIES[key][1]
except ProgrammingError:
logger.exception("Can't get config entry for %s.", key)
return None
return _deserialize_value(key, value)
示例4: create_db_comments
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def create_db_comments(table_name, table_comment, column_comments=None):
"""Populate comments for non-model tables (like Django-specific tables)"""
if connection.vendor != 'postgresql':
return
with connection.cursor() as cursor:
try:
cursor.execute(
'comment on table "{}" is %s'.format(table_name), [table_comment]
)
except ProgrammingError:
print(_exception_message)
if column_comments is not None:
for column, comment in column_comments.items():
try:
cursor.execute(
'comment on column "{}"."{}" is %s'.format(table_name, column), [comment]
)
except ProgrammingError as e:
print('{} -- {}'.format(_exception_message, e))
示例5: check_users
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [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
示例6: check_revision
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [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
示例7: set_kc_require_auth
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def set_kc_require_auth(user_id, require_auth):
"""
Configure whether or not authentication is required to see and submit data
to a user's projects.
WRITES to KobocatUserProfile.require_auth
:param int user_id: ID/primary key of the :py:class:`User` object.
:param bool require_auth: The desired setting.
"""
user = User.objects.get(pk=user_id)
_trigger_kc_profile_creation(user)
token, _ = Token.objects.get_or_create(user=user)
with transaction.atomic():
try:
profile = KobocatUserProfile.objects.get(user_id=user_id)
except ProgrammingError as e:
raise ProgrammingError('set_kc_require_auth error accessing '
'kobocat tables: {}'.format(repr(e)))
else:
if profile.require_auth != require_auth:
profile.require_auth = require_auth
profile.save()
示例8: test_synced_tenant_apps
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def test_synced_tenant_apps(self):
with TenantModel.objects.first():
# Expected synced apps
self.assertEqual(2, Catalog.objects.count())
self.assertEqual(1, TenantData.objects.count())
self.assertEqual(1, User.objects.count())
# Direct and reverse relations
self.assertEqual(User.objects.first(), TenantData.objects.first().user)
self.assertEqual(User.objects.first().tenant_objects.first(), TenantData.objects.first())
self.assertEqual(Catalog.objects.first(), TenantData.objects.first().catalog)
self.assertEqual(Catalog.objects.first().tenant_objects.first(), TenantData.objects.first())
# Not expected synced apps
with self.assertRaises(ProgrammingError):
list(MainData.objects.all())
with self.assertRaises(ProgrammingError):
list(BlogEntry.objects.all())
示例9: test_cross_authentication
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def test_cross_authentication(self):
with SchemaDescriptor.create(schema_name="www"):
self.assertTrue(authenticate(email="main@test.com", password="weakpassword")) # good
self.assertFalse(authenticate(email="blog@test.com", password="weakpassword")) # bad
self.assertFalse(authenticate(email="tenant@test.com", password="weakpassword")) # bad
with SchemaDescriptor.create(schema_name="blog"):
self.assertTrue(authenticate(email="blog@test.com", password="weakpassword")) # good
self.assertFalse(authenticate(email="main@test.com", password="weakpassword")) # bad
self.assertFalse(authenticate(email="tenant@test.com", password="weakpassword")) # bad
with TenantModel.objects.first():
self.assertTrue(authenticate(email="tenant@test.com", password="weakpassword")) # good
self.assertFalse(authenticate(email="main@test.com", password="weakpassword")) # bad
self.assertFalse(authenticate(email="blog@test.com", password="weakpassword")) # bad
# Switching to public schema
TenantModel.deactivate_all()
with self.assertRaises(ProgrammingError):
authenticate(email="unexisting@test.com", password="unexisting") # unexisting, error
示例10: __init__
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def __init__(self, *args, **kwargs):
"""
Add the residence ChoiceField on the serializer based on the existence
of Residence models
:param args: arguments
:param kwargs: keyword arguments
"""
super().__init__(*args, **kwargs)
try:
residences = Residence.objects.all()
except ProgrammingError:
residences = list()
self.fields['residence'] = serializers.ChoiceField(
choices=[
(residence.id, residence.name)
for residence in residences
],
write_only=True,
)
示例11: _validate_lookup
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def _validate_lookup(self, question, lookup):
try:
valid_lookups = self.VALID_LOOKUPS[question.type]
except KeyError: # pragma: no cover
# Not covered in tests - this only happens when you add a new
# question type and forget to update the lookup config above. In
# that case, the fix is simple - go up a few lines and adjust the
# VALID_LOOKUPS dict.
raise ProgrammingError(
f"Valid lookups not configured for question type {question.type}"
)
if lookup not in valid_lookups:
raise exceptions.ValidationError(
f"Invalid lookup for question slug={question.slug} ({question.type.upper()}): {lookup.upper()}"
)
示例12: get_max_notification_id
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def get_max_notification_id(self) -> int:
assert self.notification_id_name
try:
objects = self.record_class.objects # type: ignore
if hasattr(self.record_class, "application_name"):
objects = objects.filter(application_name=self.application_name)
if hasattr(self.record_class, "pipeline_id"):
objects = objects.filter(pipeline_id=self.pipeline_id)
latest = objects.latest(self.notification_id_name)
return getattr(latest, self.notification_id_name)
except (self.record_class.DoesNotExist, ProgrammingError): # type: ignore
return 0
示例13: database_status
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def database_status(self):
"""Collect database connection information.
:returns: A dict of db connection info.
"""
try:
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT datname AS database,
numbackends as database_connections
FROM pg_stat_database
"""
)
raw = cursor.fetchall()
# get pg_stat_database column names
names = [desc[0] for desc in cursor.description]
except (InterfaceError, NotSupportedError, OperationalError, ProgrammingError) as exc:
LOG.warning("Unable to connect to DB: %s", str(exc))
return {"ERROR": str(exc)}
# transform list-of-lists into list-of-dicts including column names.
result = [dict(zip(names, row)) for row in raw]
return result
示例14: handle
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def handle(self, *args: Any, **options: Any) -> None:
try:
# first check if the db has been initialized
Realm.objects.first()
except ProgrammingError:
raise CommandError("The Zulip database does not appear to exist. "
"Have you run initialize-database?")
url = generate_realm_creation_url(by_admin=True)
self.stdout.write(self.style.SUCCESS("Please visit the following "
"secure single-use link to register your "))
self.stdout.write(self.style.SUCCESS("new Zulip organization:\033[0m"))
self.stdout.write("")
self.stdout.write(self.style.SUCCESS(f" \033[1;92m{url}\033[0m"))
self.stdout.write("")
示例15: destroy_test_databases
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import ProgrammingError [as 別名]
def destroy_test_databases(worker_id: Optional[int]=None) -> None:
for alias in connections:
connection = connections[alias]
try:
# In the parallel mode, the test databases are created
# through the N=self.parallel child processes, and in the
# parent process (which calls `destroy_test_databases`),
# `settings_dict` remains unchanged, with the original
# template database name (zulip_test_template). So to
# delete the database zulip_test_template_<number>, we
# need to pass `number` to `destroy_test_db`.
#
# When we run in serial mode (self.parallel=1), we don't
# fork and thus both creation and destruction occur in the
# same process, which means `settings_dict` has been
# updated to have `zulip_test_template_<number>` as its
# database name by the creation code. As a result, to
# delete that database, we need to not pass a number
# argument to destroy_test_db.
if worker_id is not None:
"""Modified from the Django original to """
database_id = get_database_id(worker_id)
connection.creation.destroy_test_db(suffix=database_id)
else:
connection.creation.destroy_test_db()
except ProgrammingError:
# DB doesn't exist. No need to do anything.
pass