Skip to content

Instantly share code, notes, and snippets.

@valtron
Created February 25, 2014 18:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valtron/9215258 to your computer and use it in GitHub Desktop.
Save valtron/9215258 to your computer and use it in GitHub Desktop.
Context manager for collecting queries executed in a Django environment.
class CaptureQueries(object):
"""
Context manager that captures queries executed by the specified connection.
Mostly copied from django.test.utils.CaptureQueriesContext.
"""
def __init__(self, connection = None):
if connection is None:
from django import db
connection = db.connection
self._conn = connection
self._count_initial = 0
self.queries = []
def __enter__(self):
self._use_debug_cursor = self._conn.use_debug_cursor
self._conn.use_debug_cursor = True
self._count_initial = len(self._conn.queries)
return self
def __exit__(self, exc_type, exc_value, traceback):
self._conn.use_debug_cursor = self._use_debug_cursor
if exc_type is not None:
return
self.queries = self._conn.queries[self._count_initial:]
# Sample usage:
#
# with CaptureQueries() as cq:
# ...
# print cq.queries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment