Python django.db.connections.all() Examples
The following are 30
code examples of django.db.connections.all().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.db.connections
, or try the search function
.
Example #1
Source File: base.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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
Example #2
Source File: apps.py From bioforum with MIT License | 6 votes |
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)
Example #3
Source File: middleware.py From django-querycount with MIT License | 6 votes |
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']
Example #4
Source File: middleware.py From django-querycount with MIT License | 6 votes |
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
Example #5
Source File: signals.py From python2017 with MIT License | 6 votes |
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()
Example #6
Source File: task_utils.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 6 votes |
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
Example #7
Source File: testcases.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
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()
Example #8
Source File: signals.py From bioforum with MIT License | 6 votes |
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()
Example #9
Source File: signals.py From python with Apache License 2.0 | 6 votes |
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()
Example #10
Source File: signals.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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()
Example #11
Source File: sql.py From scout_apm_python with MIT License | 6 votes |
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")
Example #12
Source File: testcases.py From openhgsenti with Apache License 2.0 | 5 votes |
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)
Example #13
Source File: middleware.py From graphene-django with MIT License | 5 votes |
def enable_instrumentation(self): # This is thread-safe because database connections are thread-local. for connection in connections.all(): wrap_cursor(connection, self)
Example #14
Source File: testcases.py From openhgsenti with Apache License 2.0 | 5 votes |
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
Example #15
Source File: middleware.py From graphene-django with MIT License | 5 votes |
def disable_instrumentation(self): for connection in connections.all(): unwrap_cursor(connection)
Example #16
Source File: mixins.py From django-mmc with GNU General Public License v2.0 | 5 votes |
def __mmc_get_queries(self, queries=0): for db in connections.all(): queries += len(db.queries) return queries
Example #17
Source File: middleware.py From graphene-django with MIT License | 5 votes |
def get_debug_promise(self): if not self.debug_promise: self.debug_promise = Promise.all(self.promises) self.promises = [] return self.debug_promise.then(self.on_resolve_all_promises)
Example #18
Source File: testcases.py From openhgsenti with Apache License 2.0 | 5 votes |
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) )
Example #19
Source File: testcases.py From openhgsenti with Apache License 2.0 | 5 votes |
def connections_support_transactions(): """ Returns True if all connections support transactions. """ return all(conn.features.supports_transactions for conn in connections.all())
Example #20
Source File: testcases.py From python with Apache License 2.0 | 5 votes |
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) )
Example #21
Source File: testcases.py From openhgsenti with Apache License 2.0 | 5 votes |
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]
Example #22
Source File: signals.py From openhgsenti with Apache License 2.0 | 5 votes |
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 tz_sql = conn.ops.set_time_zone_sql() if tz_sql: with conn.cursor() as cursor: cursor.execute(tz_sql, [conn.timezone_name])
Example #23
Source File: testcases.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def tearDownClass(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.join() # Restore sqlite connections' non-sharability for conn in connections.all(): if (conn.settings_dict['ENGINE'].rsplit('.', 1)[-1] in ('sqlite3', 'spatialite') and conn.settings_dict['NAME'] == ':memory:'): conn.allow_thread_sharing = False super(LiveServerTestCase, cls).tearDownClass()
Example #24
Source File: testcases.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def _fixture_teardown(self): # Roll back any pending transactions in order to avoid a deadlock # during flush when TEST_MIRROR is used (#18984). for conn in connections.all(): conn.rollback_unless_managed() for db in self._databases_names(include_mirrors=False): call_command('flush', verbosity=0, interactive=False, database=db, skip_validation=True, reset_sequences=False)
Example #25
Source File: testcases.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def _databases_names(self, 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(self, '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]
Example #26
Source File: signals.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
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._localtime = None # 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])
Example #27
Source File: db.py From aws-xray-sdk-python with Apache License 2.0 | 5 votes |
def patch_db(): for conn in connections.all(): module = importlib.import_module(conn.__module__) _patch_conn(getattr(module, conn.__class__.__name__))
Example #28
Source File: testcases.py From python with Apache License 2.0 | 5 votes |
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() # Restore sqlite in-memory database connections' non-shareability for conn in connections.all(): if conn.vendor == 'sqlite' and conn.is_in_memory_db(): conn.allow_thread_sharing = False
Example #29
Source File: testcases.py From python with Apache License 2.0 | 5 votes |
def setUpClass(cls): super(LiveServerTestCase, cls).setUpClass() connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if conn.vendor == 'sqlite' and conn.is_in_memory_db(): # Explicitly enable thread-shareability for this connection conn.allow_thread_sharing = True connections_override[conn.alias] = conn cls._live_server_modified_settings = modify_settings( ALLOWED_HOSTS={'append': cls.host}, ) cls._live_server_modified_settings.enable() cls.server_thread = cls._create_server_thread(connections_override) cls.server_thread.daemon = True cls.server_thread.start() # Wait for the live server to be ready cls.server_thread.is_ready.wait() if cls.server_thread.error: # Clean up behind ourselves, since tearDownClass won't get called in # case of errors. cls._tearDownClassInternal() raise cls.server_thread.error
Example #30
Source File: testcases.py From python with Apache License 2.0 | 5 votes |
def connections_support_transactions(): """ Returns True if all connections support transactions. """ return all(conn.features.supports_transactions for conn in connections.all())