Created
June 13, 2019 14:33
-
-
Save MarkusH/273fe8824583492b15b601f0387123fe to your computer and use it in GitHub Desktop.
Warn on too many queries in context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from contextlib import contextmanager | |
from inspect import getframeinfo, stack | |
from django.db import connections | |
logger = logging.getLogger(__name__) | |
@contextmanager | |
def warn_too_many_queries(*, threshold, using="default"): | |
""" | |
Log a warning when too many queries were executed within a context. | |
For example, the following code will raise a warning if there's at | |
least 3 books:: | |
with warn_too_many_queries(threshold=3): | |
for book in Book.objects.all(): | |
print(f"{book.title} by {book.author.name}") | |
# Too many queries at myapp/views.py:12 | |
""" | |
num_queries = len(connections[using].queries) | |
yield | |
new_num_queries = len(connections[using].queries) | |
diff = new_num_queries - num_queries | |
if diff > threshold: | |
caller = getframeinfo(stack()[1][0]) | |
logger.warning(f"Too many queries at %s:%s", caller.filename, caller.lineno) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment