Coverage for recipes/middleware.py: 0%
46 statements
« prev ^ index » next coverage.py v7.4.0, created at 2023-12-29 00:47 +0100
« prev ^ index » next coverage.py v7.4.0, created at 2023-12-29 00:47 +0100
1from os import getenv
3from django.conf import settings
4from django.contrib.auth.middleware import RemoteUserMiddleware
5from django.db import connection
8class CustomRemoteUser(RemoteUserMiddleware):
9 header = getenv('PROXY_HEADER', 'HTTP_REMOTE_USER')
12"""
13Gist code by vstoykov, you can check his original gist at:
14https://gist.github.com/vstoykov/1390853/5d2e8fac3ca2b2ada8c7de2fb70c021e50927375
15Changes:
16Ignoring static file requests and a certain useless admin request from triggering the logger.
17Updated statements to make it Python 3 friendly.
18"""
21def terminal_width():
22 """
23 Function to compute the terminal width.
24 """
25 width = 0
26 try:
27 import fcntl
28 import struct
29 import termios
30 s = struct.pack('HHHH', 0, 0, 0, 0)
31 x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)
32 width = struct.unpack('HHHH', x)[1]
33 except Exception:
34 pass
35 if width <= 0:
36 try:
37 width = int(getenv['COLUMNS'])
38 except Exception:
39 pass
40 if width <= 0:
41 width = 80
42 return width
45def SqlPrintingMiddleware(get_response):
46 def middleware(request):
47 response = get_response(request)
48 if (
49 not settings.DEBUG
50 or len(connection.queries) == 0
51 or request.path_info.startswith(settings.MEDIA_URL)
52 or '/admin/jsi18n/' in request.path_info
53 ):
54 return response
56 indentation = 2
57 print("\n\n%s\033[1;35m[SQL Queries for]\033[1;34m %s\033[0m\n" % (" " * indentation, request.path_info))
58 width = terminal_width()
59 total_time = 0.0
60 for query in connection.queries:
61 nice_sql = query['sql'].replace('"', '').replace(',', ', ')
62 sql = "\033[1;31m[%s]\033[0m %s" % (query['time'], nice_sql)
63 total_time = total_time + float(query['time'])
64 while len(sql) > width - indentation:
65 # print("%s%s" % (" " * indentation, sql[:width - indentation]))
66 sql = sql[width - indentation:]
67 # print("%s%s\n" % (" " * indentation, sql))
68 replace_tuple = (" " * indentation, str(total_time))
69 print("%s\033[1;32m[TOTAL TIME: %s seconds]\033[0m" % replace_tuple)
70 print("%s\033[1;32m[TOTAL QUERIES: %s]\033[0m" % (" " * indentation, len(connection.queries)))
71 return response
72 return middleware