当前位置: 首页>>代码示例>>Python>>正文


Python connections.all方法代码示例

本文整理汇总了Python中django.db.connections.all方法的典型用法代码示例。如果您正苦于以下问题:Python connections.all方法的具体用法?Python connections.all怎么用?Python connections.all使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.connections的用法示例。


在下文中一共展示了connections.all方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update_connections_time_zone

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def update_connections_time_zone(**kwargs):
    if kwargs['setting'] == 'TIME_ZONE':
        # Reset process time zone
        if hasattr(time, 'tzset'):
            if kwargs['value']:
                os.environ['TZ'] = kwargs['value']
            else:
                os.environ.pop('TZ', None)
            time.tzset()

        # Reset local time zone cache
        timezone.get_default_timezone.cache_clear()

    # Reset the database connections' time zone
    if kwargs['setting'] in {'TIME_ZONE', 'USE_TZ'}:
        for conn in connections.all():
            try:
                del conn.timezone
            except AttributeError:
                pass
            try:
                del conn.timezone_name
            except AttributeError:
                pass
            conn.ensure_timezone() 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:27,代码来源:signals.py

示例2: ready

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def ready(self):
        # Connections may already exist before we are called.
        for conn in connections.all():
            if conn.vendor == 'postgresql':
                conn.introspection.data_types_reverse.update({
                    3802: 'django.contrib.postgresql.fields.JSONField',
                    3904: 'django.contrib.postgresql.fields.IntegerRangeField',
                    3906: 'django.contrib.postgresql.fields.FloatRangeField',
                    3910: 'django.contrib.postgresql.fields.DateTimeRangeField',
                    3912: 'django.contrib.postgresql.fields.DateRangeField',
                    3926: 'django.contrib.postgresql.fields.BigIntegerRangeField',
                })
                if conn.connection is not None:
                    register_type_handlers(conn)
        connection_created.connect(register_type_handlers)
        CharField.register_lookup(Unaccent)
        TextField.register_lookup(Unaccent)
        CharField.register_lookup(SearchLookup)
        TextField.register_lookup(SearchLookup)
        CharField.register_lookup(TrigramSimilar)
        TextField.register_lookup(TrigramSimilar) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:23,代码来源:apps.py

示例3: __init__

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def __init__(self, *args, **kwargs):
        # Call super first, so the MiddlewareMixin's __init__ does its thing.
        super(QueryCountMiddleware, self).__init__(*args, **kwargs)

        if settings.DEBUG:
            self.request_path = None
            self.stats = {"request": {}, "response": {}}
            self.dbs = [c.alias for c in connections.all()]
            self.queries = Counter()
            self._reset_stats()

            self._start_time = None
            self._end_time = None
            self.host = None  # The HTTP_HOST pulled from the request

            # colorizing methods
            self.white = termcolors.make_style(opts=('bold',), fg='white')
            self.red = termcolors.make_style(opts=('bold',), fg='red')
            self.yellow = termcolors.make_style(opts=('bold',), fg='yellow')
            self.green = termcolors.make_style(fg='green')

            # query type detection regex
            # TODO: make stats classification regex more robust
            self.threshold = QC_SETTINGS['THRESHOLDS'] 
开发者ID:bradmontgomery,项目名称:django-querycount,代码行数:26,代码来源:middleware.py

示例4: _count_queries

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def _count_queries(self, which):
        for c in connections.all():
            for q in c.queries:
                if not self._ignore_sql(q):
                    if q.get('sql') and self.READ_QUERY_REGEX.search(q['sql']) is not None:
                        self.stats[which][c.alias]['reads'] += 1
                    else:
                        self.stats[which][c.alias]['writes'] += 1
                    self.stats[which][c.alias]['total'] += 1
                    self.queries[q['sql']] += 1

            # We'll show the worst offender; i.e. the query with the most duplicates
            duplicates = self.queries.most_common(1)
            if duplicates:
                sql, count = duplicates[0]
                self.stats[which][c.alias]['duplicates'] = count
            else:
                self.stats[which][c.alias]['duplicates'] = 0 
开发者ID:bradmontgomery,项目名称:django-querycount,代码行数:20,代码来源:middleware.py

示例5: prepare_task_execution

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def prepare_task_execution():
        """

        Clearing of old database connections for CONN_MAX_AGE option (database connection settings)

        """
        if not TaskUtils.is_celery_worker():
            return

        try:
            if TaskUtils.__connection_initialization_finished:
                close_old_connections()
            else:
                for conn in connections.all():
                    conn.close()
                    TaskUtils.__connection_initialization_finished = True
        except Exception:
            pass 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:20,代码来源:task_utils.py

示例6: _nodb_connection

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def _nodb_connection(self):
        nodb_connection = super()._nodb_connection
        try:
            nodb_connection.ensure_connection()
        except (Database.DatabaseError, WrappedDatabaseError):
            warnings.warn(
                "Normally Django will use a connection to the 'postgres' database "
                "to avoid running initialization queries against the production "
                "database when it's not needed (for example, when running tests). "
                "Django was unable to create a connection to the 'postgres' database "
                "and will use the first PostgreSQL database instead.",
                RuntimeWarning
            )
            for connection in connections.all():
                if connection.vendor == 'postgresql' and connection.settings_dict['NAME'] != 'postgres':
                    return self.__class__(
                        {**self.settings_dict, 'NAME': connection.settings_dict['NAME']},
                        alias=self.alias,
                        allow_thread_sharing=False,
                    )
        return nodb_connection 
开发者ID:PacktPublishing,项目名称:Hands-On-Application-Development-with-PyCharm,代码行数:23,代码来源:base.py

示例7: _post_teardown

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def _post_teardown(self):
        """ Performs any post-test things. This includes:

            * Putting back the original ROOT_URLCONF if it was changed.
            * Force closing the connection, so that the next test gets
              a clean cursor.
        """
        self._fixture_teardown()
        self._urlconf_teardown()
        # Some DB cursors include SQL statements as part of cursor
        # creation. If you have a test that does rollback, the effect
        # of these statements is lost, which can effect the operation
        # of tests (e.g., losing a timezone setting causing objects to
        # be created with the wrong time).
        # To make sure this doesn't happen, get a clean connection at the
        # start of every test.
        for conn in connections.all():
            conn.close() 
开发者ID:blackye,项目名称:luscan-devel,代码行数:20,代码来源:testcases.py

示例8: ensure_sql_instrumented

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def ensure_sql_instrumented():
    global sql_instrumented
    if sql_instrumented:
        return
    sql_instrumented = True

    if django.VERSION >= (2, 0):
        for connection in connections.all():
            install_db_execute_hook(connection=connection)
        connection_created.connect(install_db_execute_hook)
        logger.debug("Installed DB connection created signal handler")
    else:

        CursorWrapper.execute = execute_wrapper(CursorWrapper.execute)
        CursorWrapper.executemany = executemany_wrapper(CursorWrapper.executemany)

        logger.debug("Monkey patched SQL") 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:19,代码来源:sql.py

示例9: update_connections_time_zone

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def update_connections_time_zone(**kwargs):
    if kwargs['setting'] == 'TIME_ZONE':
        # Reset process time zone
        if hasattr(time, 'tzset'):
            if kwargs['value']:
                os.environ['TZ'] = kwargs['value']
            else:
                os.environ.pop('TZ', None)
            time.tzset()

        # Reset local time zone cache
        timezone.get_default_timezone.cache_clear()

    # Reset the database connections' time zone
    if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz]) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:29,代码来源:signals.py

示例10: _databases_names

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def _databases_names(cls, include_mirrors=True):
        # If the test case has a multi_db=True flag, act on all databases,
        # including mirrors or not. Otherwise, just on the default DB.
        if getattr(cls, 'multi_db', False):
            return [alias for alias in connections
                    if include_mirrors or not connections[alias].settings_dict['TEST']['MIRROR']]
        else:
            return [DEFAULT_DB_ALIAS] 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:10,代码来源:testcases.py

示例11: _post_teardown

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def _post_teardown(self):
        """Performs any post-test things. This includes:

        * Flushing the contents of the database, to leave a clean slate. If
          the class has an 'available_apps' attribute, post_migrate isn't fired.
        * Force-closing the connection, so the next test gets a clean cursor.
        """
        try:
            self._fixture_teardown()
            super(TransactionTestCase, self)._post_teardown()
            if self._should_reload_connections():
                # Some DB cursors include SQL statements as part of cursor
                # creation. If you have a test that does a rollback, the effect
                # of these statements is lost, which can affect the operation of
                # tests (e.g., losing a timezone setting causing objects to be
                # created with the wrong time). To make sure this doesn't
                # happen, get a clean connection at the start of every test.
                for conn in connections.all():
                    conn.close()
        finally:
            if self.available_apps is not None:
                apps.unset_available_apps()
                setting_changed.send(sender=settings._wrapped.__class__,
                                     setting='INSTALLED_APPS',
                                     value=settings.INSTALLED_APPS,
                                     enter=False) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:28,代码来源:testcases.py

示例12: connections_support_transactions

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def connections_support_transactions():
    """
    Returns True if all connections support transactions.
    """
    return all(conn.features.supports_transactions
               for conn in connections.all()) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:8,代码来源:testcases.py

示例13: skipUnlessDBFeature

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def skipUnlessDBFeature(*features):
    """
    Skip a test unless a database has all the named features.
    """
    return _deferredSkip(
        lambda: not all(getattr(connection.features, feature, False) for feature in features),
        "Database doesn't support feature(s): %s" % ", ".join(features)
    ) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:10,代码来源:testcases.py

示例14: _tearDownClassInternal

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def _tearDownClassInternal(cls):
        # There may not be a 'server_thread' attribute if setUpClass() for some
        # reasons has raised an exception.
        if hasattr(cls, 'server_thread'):
            # Terminate the live server's thread
            cls.server_thread.terminate()
            cls.server_thread.join()

        # Restore sqlite in-memory database connections' non-shareability
        for conn in connections.all():
            if conn.vendor == 'sqlite' and conn.is_in_memory_db(conn.settings_dict['NAME']):
                conn.allow_thread_sharing = False 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:14,代码来源:testcases.py

示例15: make_view_atomic

# 需要导入模块: from django.db import connections [as 别名]
# 或者: from django.db.connections import all [as 别名]
def make_view_atomic(self, view):
        non_atomic_requests = getattr(view, '_non_atomic_requests', set())
        for db in connections.all():
            if (db.settings_dict['ATOMIC_REQUESTS']
                    and db.alias not in non_atomic_requests):
                view = transaction.atomic(using=db.alias)(view)
        return view 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:9,代码来源:base.py


注:本文中的django.db.connections.all方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。