Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented qinspect as a context manager. #29

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions qinspect/manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import time
from django.db import connection
from qinspect.middleware import QueryInspectMiddleware, cfg


class QueryInspectContextManager():
"""
Code called within this context manager is profiled by django-queryinspect.
The results will be presented when the context manager exits.
"""

def __enter__(self):
if cfg['enabled']:
self.request_start = time.time()
self.conn_queries_len = len(connection.queries)
return self

def __exit__(self, exc_type, exc_value, exc_traceback):
if cfg['enabled']:
request_time = time.time() - self.request_start

infos = QueryInspectMiddleware.get_query_infos(
connection.queries[self.conn_queries_len:])

num_duplicates = QueryInspectMiddleware.check_duplicates(infos)
QueryInspectMiddleware.check_stddev_limit(infos)
QueryInspectMiddleware.check_absolute_limit(infos)
# Can call ootput_states() with response={} because the only thing
# it does to response is add keys.
QueryInspectMiddleware.output_stats(
infos, num_duplicates, request_time, {})
1 change: 1 addition & 0 deletions qinspect/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def check_duplicates(cls, infos):

return n

@classmethod
def check_stddev_limit(cls, infos):
total = sum(qi.time for qi in infos)
n = len(infos)
Expand Down