Add a middleware to count queries

- https://www.dabapps.com/blog/logging-sql-queries-django-13/
This commit is contained in:
Oliver Walters 2019-05-20 18:51:57 +10:00
parent fc75ab7420
commit 34620b22b0
3 changed files with 44 additions and 19 deletions

View File

@ -1,5 +1,9 @@
from django.shortcuts import HttpResponseRedirect
from django.urls import reverse_lazy
from django.db import connection
import logging
logger = logging.getLogger(__name__)
class AuthRequiredMiddleware(object):
@ -24,3 +28,40 @@ class AuthRequiredMiddleware(object):
# the view is called.
return response
class QueryCountMiddleware(object):
"""
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.
Reference: https://www.dabapps.com/blog/logging-sql-queries-django-13/
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if response.status_code == 200:
total_time = 0
if len(connection.queries) > 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)
logger.debug('%s queries run, total %s seconds' % (len(connection.queries), total_time))
return response

View File

@ -86,6 +86,9 @@ MIDDLEWARE = [
'InvenTree.middleware.AuthRequiredMiddleware'
]
if DEBUG:
MIDDLEWARE.append('InvenTree.middleware.QueryCountMiddleware')
ROOT_URLCONF = 'InvenTree.urls'
TEMPLATES = [

View File

@ -85,25 +85,6 @@
<td>{{ part.allocation_count }}</td>
</tr>
{% endif %}
{% if part.supplier_count > 0 %}
<tr>
<td>
Price
</td>
<td>
{% if part.min_single_price %}
{% if part.min_single_price == part.max_single_price %}
{{ part.min_single_price }}
{% else %}
{{ part.min_single_price }} to {{ part.max_single_price }}
{% endif %}
from {{ part.supplier_count }} suppliers.
{% else %}
<span class='warning-msg'><i>No pricing data avilable</i></span>
{% endif %}
</td>
</tr>
{% endif %}
</table>
</div>
</div>