| 1 |
import io |
| 2 |
import os |
| 3 |
import sys |
| 4 |
import time |
| 5 |
|
| 6 |
from django.conf import settings |
| 7 |
from django.http import HttpResponse |
| 8 |
from django.utils.module_loading import import_string |
| 9 |
|
| 10 |
from pyinstrument import Profiler |
| 11 |
from pyinstrument.renderers import Renderer |
| 12 |
from pyinstrument.renderers.html import HTMLRenderer |
| 13 |
|
| 14 |
try: |
| 15 |
from django.utils.deprecation import MiddlewareMixin |
| 16 |
except ImportError: |
| 17 |
MiddlewareMixin = object |
| 18 |
|
| 19 |
|
| 20 |
def get_renderer(path) -> Renderer: |
| 21 |
"""Return the renderer instance.""" |
| 22 |
if path: |
| 23 |
try: |
| 24 |
renderer = import_string(path)() |
| 25 |
except ImportError as exc: |
| 26 |
print("Unable to import the class: %s" % path) |
| 27 |
raise exc |
| 28 |
|
| 29 |
if not isinstance(renderer, Renderer): |
| 30 |
raise ValueError(f"Renderer should subclass: {Renderer}") |
| 31 |
|
| 32 |
return renderer |
| 33 |
else: |
| 34 |
return HTMLRenderer() |
| 35 |
|
| 36 |
|
| 37 |
class ProfilerMiddleware(MiddlewareMixin): |
| 38 |
def process_request(self, request): |
| 39 |
profile_dir = getattr(settings, "PYINSTRUMENT_PROFILE_DIR", None) |
| 40 |
|
| 41 |
func_or_path = getattr(settings, "PYINSTRUMENT_SHOW_CALLBACK", None) |
| 42 |
if isinstance(func_or_path, str): |
| 43 |
show_pyinstrument = import_string(func_or_path) |
| 44 |
elif callable(func_or_path): |
| 45 |
show_pyinstrument = func_or_path |
| 46 |
else: |
| 47 |
show_pyinstrument = lambda request: True |
| 48 |
|
| 49 |
if ( |
| 50 |
show_pyinstrument(request) |
| 51 |
and getattr(settings, "PYINSTRUMENT_URL_ARGUMENT", "profile") in request.GET |
| 52 |
) or profile_dir: |
| 53 |
interval: float = getattr(settings, "PYINSTRUMENT_INTERVAL", 0.001) |
| 54 |
profiler = Profiler(interval=interval) |
| 55 |
profiler.start() |
| 56 |
|
| 57 |
request.profiler = profiler |
| 58 |
|
| 59 |
def process_response(self, request, response): |
| 60 |
if hasattr(request, "profiler"): |
| 61 |
profile_session = request.profiler.stop() |
| 62 |
default_filename_template = "{total_time:.3f}s {path} {timestamp:.0f}.{ext}" |
| 63 |
|
| 64 |
configured_renderer = getattr(settings, "PYINSTRUMENT_PROFILE_DIR_RENDERER", None) |
| 65 |
renderer = get_renderer(configured_renderer) |
| 66 |
|
| 67 |
output = renderer.render(profile_session) |
| 68 |
|
| 69 |
profile_dir = getattr(settings, "PYINSTRUMENT_PROFILE_DIR", None) |
| 70 |
|
| 71 |
filename_cb = getattr(settings, "PYINSTRUMENT_FILENAME_CALLBACK", None) |
| 72 |
|
| 73 |
filename_template = getattr( |
| 74 |
settings, "PYINSTRUMENT_FILENAME", default_filename_template |
| 75 |
) |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
path = request.get_full_path().replace("/", "_")[:100] |
| 80 |
|
| 81 |
|
| 82 |
if sys.platform in ["win32", "cygwin"]: |
| 83 |
path = path.replace("?", "_qs_") |
| 84 |
|
| 85 |
if profile_dir: |
| 86 |
if filename_cb and callable(filename_cb): |
| 87 |
filename = filename_cb(request, profile_session, renderer) |
| 88 |
if not isinstance(filename, str): |
| 89 |
raise ValueError("Filename callback return value should be a string") |
| 90 |
else: |
| 91 |
filename = filename_template.format( |
| 92 |
total_time=profile_session.duration, |
| 93 |
path=path, |
| 94 |
timestamp=time.time(), |
| 95 |
ext=renderer.output_file_extension, |
| 96 |
) |
| 97 |
|
| 98 |
file_path = os.path.join(profile_dir, filename) |
| 99 |
|
| 100 |
if not os.path.exists(profile_dir): |
| 101 |
os.mkdir(profile_dir) |
| 102 |
|
| 103 |
with open(file_path, "w", encoding="utf-8") as f: |
| 104 |
f.write(output) |
| 105 |
|
| 106 |
if getattr(settings, "PYINSTRUMENT_URL_ARGUMENT", "profile") in request.GET: |
| 107 |
if isinstance(renderer, HTMLRenderer): |
| 108 |
return HttpResponse(output) |
| 109 |
else: |
| 110 |
renderer = HTMLRenderer() |
| 111 |
output = renderer.render(profile_session) |
| 112 |
return HttpResponse(output) |
| 113 |
else: |
| 114 |
return response |
| 115 |
else: |
| 116 |
return response |