Created
August 29, 2019 10:56
-
-
Save sanjaykrishnan/146eeb11064995eb5e9068c36638af1d to your computer and use it in GitHub Desktop.
Mixin to print query count and time of execution.
This file contains hidden or 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
from django.db import connection | |
from django.http import HttpResponse | |
from django.utils.deprecation import MiddlewareMixin | |
# from django.utils.log import getLogger | |
# logger = getLogger(__name__) | |
class QueryCountDebugMiddleware(MiddlewareMixin): | |
""" | |
This middleware will log the number of queries run | |
and the total time taken for each request (with a | |
status code of 200). It does not currently support | |
multi-db setups. | |
""" | |
def process_exception(self, request, exception): | |
return HttpResponse("Exception occured..") | |
def process_response(self, request, response): | |
if response.status_code == 200: | |
total_time = 0 | |
for query in connection.queries: | |
query_time = query.get('time') | |
if query_time is None: | |
# django-debug-toolbar monkeypatches the connection | |
# cursor wrapper and adds extra information in each | |
# item in connection.queries. The query time is stored | |
# under the key "duration" rather than "time" and is | |
# in milliseconds, not seconds. | |
query_time = query.get('duration', 0) / 1000 | |
total_time += float(query_time) | |
print('%s queries run, total %s seconds' % (len(connection.queries), total_time)) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment