Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created June 4, 2014 13:53
Show Gist options
  • Save igniteflow/f376cc2e13c8f68800b1 to your computer and use it in GitHub Desktop.
Save igniteflow/f376cc2e13c8f68800b1 to your computer and use it in GitHub Desktop.
Useful debugging context managers for Django
import logging
from contextlib import contextmanager
from django.db.backends import BaseDatabaseWrapper
from django.db.backends.util import CursorWrapper
@contextmanager
def turn_off_sql_logging():
"""disables SQL logging, useful for local development to filter out noise"""
make_debug_cursor = BaseDatabaseWrapper.make_debug_cursor
if settings.DEBUG:
BaseDatabaseWrapper.make_debug_cursor = lambda self, cursor: CursorWrapper(cursor, self)
yield
BaseDatabaseWrapper.make_debug_cursor = make_debug_cursor
@contextmanager
def count_queries():
"""logs number of queries made"""
before = len(connection.queries)
yield
after = len(connection.queries)
logging.debug('Queries executed: {}'.format(after - before))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment