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


Python db.connections方法代碼示例

本文整理匯總了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 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:20,代碼來源:query.py

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

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

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

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

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

示例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} 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:27,代碼來源:test_basic.py

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

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

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

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

示例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') 
開發者ID:noripyt,項目名稱:django-cachalot,代碼行數:21,代碼來源:benchmark.py

示例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) 
開發者ID:wemake-services,項目名稱:django-test-migrations,代碼行數:21,代碼來源:sql.py

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

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


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