Created
May 20, 2016 14:59
-
-
Save ustun/b1928924866aeb9bf196e108b1631ff1 to your computer and use it in GitHub Desktop.
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
class DatabaseLoggingMiddleware(object): | |
def process_request(self, request): | |
request.start_time = time.time() | |
def process_response(self, request, response): | |
if 'content-type' in response._headers and response._headers['content-type'][1].startswith('application/json') and response.status_code == 200: | |
end_time = time.time() | |
total_execution_time_msec = int((end_time - request.start_time) * 1000) | |
data = json.loads(response.content) | |
if not isinstance(data, dict): | |
return response | |
if 'meta' not in data: | |
data['meta'] = {} | |
data['meta']['n_queries'] = len(connection.queries) | |
data['meta']['queries'] = connection.queries | |
data['meta']['total_time'] = sum([float(q['time']) for q in connection.queries]) | |
data['meta']['total_execution_time'] = total_execution_time_msec / 1000.0 | |
response.content = json.dumps(data) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment