本文整理匯總了Python中django.db.connections方法的典型用法代碼示例。如果您正苦於以下問題:Python db.connections方法的具體用法?Python db.connections怎麽用?Python db.connections使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.db
的用法示例。
在下文中一共展示了db.connections方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: is_nullable
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def is_nullable(self, field):
"""
A helper to check if the given field should be treated as nullable.
Some backends treat '' as null and Django treats such fields as
nullable for those backends. In such situations field.null can be
False even if we should treat the field as nullable.
"""
# We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
# (nor should it have) knowledge of which connection is going to be
# used. The proper fix would be to defer all decisions where
# is_nullable() is needed to the compiler stage, but that is not easy
# to do currently.
if ((connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls)
and field.empty_strings_allowed):
return True
else:
return field.null
示例2: scale
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def scale(self, x, y, z=0.0, **kwargs):
"""
Scales the geometry to a new size by multiplying the ordinates
with the given x,y,z scale factors.
"""
if connections[self.db].ops.spatialite:
if z != 0.0:
raise NotImplementedError('SpatiaLite does not support 3D scaling.')
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
'procedure_args': {'x': x, 'y': y},
'select_field': GeomField(),
}
else:
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
'procedure_args': {'x': x, 'y': y, 'z': z},
'select_field': GeomField(),
}
return self._spatial_attribute('scale', s, **kwargs)
示例3: translate
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def translate(self, x, y, z=0.0, **kwargs):
"""
Translates the geometry to a new location using the given numeric
parameters as offsets.
"""
if connections[self.db].ops.spatialite:
if z != 0.0:
raise NotImplementedError('SpatiaLite does not support 3D translation.')
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
'procedure_args': {'x': x, 'y': y},
'select_field': GeomField(),
}
else:
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
'procedure_args': {'x': x, 'y': y, 'z': z},
'select_field': GeomField(),
}
return self._spatial_attribute('translate', s, **kwargs)
示例4: _geomset_attribute
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs):
"""
DRY routine for setting up a GeoQuerySet method that attaches a
Geometry attribute and takes a Geoemtry parameter. This is used
for geometry set-like operations (e.g., intersection, difference,
union, sym_difference).
"""
s = {
'geom_args': ('geom',),
'select_field': GeomField(),
'procedure_fmt': '%(geo_col)s,%(geom)s',
'procedure_args': {'geom': geom},
}
if connections[self.db].ops.oracle:
s['procedure_fmt'] += ',%(tolerance)s'
s['procedure_args']['tolerance'] = tolerance
return self._spatial_attribute(func, s, **kwargs)
示例5: has_key
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def has_key(self, key, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
db = router.db_for_read(self.cache_model_class)
table = connections[db].ops.quote_name(self._table)
if settings.USE_TZ:
now = datetime.utcnow()
else:
now = datetime.now()
now = now.replace(microsecond=0)
with connections[db].cursor() as cursor:
cursor.execute("SELECT cache_key FROM %s "
"WHERE cache_key = %%s and expires > %%s" % table,
[key, connections[db].ops.value_to_db_datetime(now)])
return cursor.fetchone() is not None
示例6: _cull
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def _cull(self, db, cursor, now):
if self._cull_frequency == 0:
self.clear()
else:
# When USE_TZ is True, 'now' will be an aware datetime in UTC.
now = now.replace(tzinfo=None)
table = connections[db].ops.quote_name(self._table)
cursor.execute("DELETE FROM %s WHERE expires < %%s" % table,
[connections[db].ops.value_to_db_datetime(now)])
cursor.execute("SELECT COUNT(*) FROM %s" % table)
num = cursor.fetchone()[0]
if num > self._max_entries:
cull_num = num // self._cull_frequency
cursor.execute(
connections[db].ops.cache_key_culling_sql() % table,
[cull_num])
cursor.execute("DELETE FROM %s "
"WHERE cache_key < %%s" % table,
[cursor.fetchone()[0]])
示例7: test_sql_psycopg2_string_composition
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [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}
示例8: check_migrations
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def check_migrations():
"""
Check the status of database migrations.
The koku API server is responsible for running all database migrations. This method
will return the state of the database and whether or not all migrations have been completed.
Hat tip to the Stack Overflow contributor: https://stackoverflow.com/a/31847406
Returns:
Boolean - True if database is available and migrations have completed. False otherwise.
"""
try:
connection = connections[DEFAULT_DB_ALIAS]
connection.prepare_database()
executor = MigrationExecutor(connection)
targets = executor.loader.graph.leaf_nodes()
return not executor.migration_plan(targets)
except OperationalError:
return False
示例9: check_migrations
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def check_migrations(self):
"""
Check the status of database migrations.
The koku API server is responsible for running all database migrations. This method
will return the state of the database and whether or not all migrations have been completed.
Hat tip to the Stack Overflow contributor: https://stackoverflow.com/a/31847406
Returns:
Boolean - True if database is available and migrations have completed. False otherwise.
"""
connection = connections[DEFAULT_DB_ALIAS]
connection.prepare_database()
executor = MigrationExecutor(connection)
targets = executor.loader.graph.leaf_nodes()
return not executor.migration_plan(targets)
示例10: testHistograms
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def testHistograms(self):
cursor_db1 = connections["test_db_1"].cursor()
cursor_db2 = connections["test_db_2"].cursor()
cursor_db1.execute("SELECT 1")
for _ in range(200):
cursor_db2.execute("SELECT 2")
assert (
self.getMetric(
"django_db_query_duration_seconds_count",
alias="test_db_1",
vendor="sqlite",
)
> 0
)
assert (
self.getMetric(
"django_db_query_duration_seconds_count",
alias="test_db_2",
vendor="sqlite",
)
>= 200
)
示例11: sql
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def sql(request):
databases = connections.databases.keys()
query = request.GET.get("query")
db = request.GET.get("database")
if query and db:
cursor = connections[db].cursor()
cursor.execute(query, [])
results = cursor.fetchall()
return TemplateResponse(
request,
"sql.html",
{"query": query, "rows": results, "databases": databases},
)
else:
return TemplateResponse(
request, "sql.html", {"query": None, "rows": None, "databases": databases}
)
示例12: run
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def run(self):
for db_alias in settings.DATABASES:
self.db_alias = db_alias
self.db_vendor = connections[self.db_alias].vendor
print('Benchmarking %s…' % self.db_vendor)
for cache_alias in settings.CACHES:
cache = caches[cache_alias]
self.cache_name = cache.__class__.__name__[:-5].lower()
with override_settings(CACHALOT_CACHE=cache_alias):
self.execute_benchmark()
self.df = pd.DataFrame.from_records(self.data)
if not os.path.exists(RESULTS_PATH):
os.mkdir(RESULTS_PATH)
self.df.to_csv(os.path.join(RESULTS_PATH, 'data.csv'))
self.xlim = (0, self.df['time'].max() * 1.01)
self.output('db')
self.output('cache')
示例13: drop_models_tables
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def drop_models_tables(
database_name: str,
style: Optional[Style] = None,
) -> None:
"""Drop all installed Django's models tables."""
style = style or no_style()
connection = connections[database_name]
tables = connection.introspection.django_table_names(
only_existing=True,
include_views=False,
)
sql_drop_tables = [
connection.SchemaEditorClass.sql_delete_table % {
'table': style.SQL_FIELD(connection.ops.quote_name(table)),
}
for table in tables
]
if sql_drop_tables:
get_execute_sql_flush_for(connection)(database_name, sql_drop_tables)
示例14: _execute_query
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def _execute_query(self):
connection = connections[self.using]
# Adapt parameters to the database, as much as possible considering
# that the target type isn't known. See #17755.
params_type = self.params_type
adapter = connection.ops.adapt_unknown_value
if params_type is tuple:
params = tuple(adapter(val) for val in self.params)
elif params_type is dict:
params = {key: adapter(val) for key, val in self.params.items()}
else:
raise RuntimeError("Unexpected params type: %s" % params_type)
self.cursor = connection.cursor()
self.cursor.execute(self.sql, params)
示例15: is_nullable
# 需要導入模塊: from django import db [as 別名]
# 或者: from django.db import connections [as 別名]
def is_nullable(self, field):
"""
Check if the given field should be treated as nullable.
Some backends treat '' as null and Django treats such fields as
nullable for those backends. In such situations field.null can be
False even if we should treat the field as nullable.
"""
# We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
# (nor should it have) knowledge of which connection is going to be
# used. The proper fix would be to defer all decisions where
# is_nullable() is needed to the compiler stage, but that is not easy
# to do currently.
if connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and field.empty_strings_allowed:
return True
else:
return field.null