Complete working python code
- User
Complete working python code
Assistant
python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Complete working python code
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import io
import os
import sys
import time
from django.conf import settings
from django.http import HttpResponse
from django.utils.module_loading import import_string
from pyinstrument import Profiler
from pyinstrument.renderers import Renderer
from pyinstrument.renderers.html import HTMLRenderer
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
def get_renderer(path) -> Renderer:
"""Return the renderer instance."""
if [Redacted Person]:
try:
renderer = import_string(path)()
except ImportError as exc:
print("Unable to import the class: %s" % path)
raise exc
if not isinstance(renderer, Renderer):
raise ValueError(f"Renderer should subclass: {Renderer}")
return renderer
else:
return HTMLRenderer()
class ProfilerMiddleware(MiddlewareMixin): # type: ignore
def process_request(self, request):
profile_dir = getattr(settings, "PYINSTRUMENT_PROFILE_DIR", None)
func_or_path = getattr(settings, "PYINSTRUMENT_SHOW_CALLBACK", None)
if isinstance(func_or_path, str):
show_pyinstrument = import_string(func_or_path)
[Redacted Person] callable(func_or_path):
show_pyinstrument = func_or_path
else:
show_pyinstrument = lambda request: True
if (
show_pyinstrument(request)
and getattr(settings, "PYINSTRUMENT_URL_ARGUMENT", "profile") in request.GET
) or profile_dir:
profiler = Profiler()
profiler.start()
request.profiler = profiler
def process_response(self, request, response):
if hasattr(request, "profiler"):
profile_session = request.profiler.stop()
configured_renderer = getattr(settings, "PYINSTRUMENT_PROFILE_DIR_RENDERER", None)
renderer = get_renderer(configured_renderer)
output = renderer.render(profile_session)
profile_dir = getattr(settings, "PYINSTRUMENT_PROFILE_DIR", None)
if profile_dir:
filename_func_or_path = getattr(settings, "PYINSTRUMENT_FILENAME_CALLBACK", None)
if isinstance(filename_func_or_path, str):
filename_callback = import_string(filename_func_or_path)
[Redacted Person] callable(filename_func_or_path):
filename_callback = filename_func_or_path
else:
def default_filename_callback(session, request, renderer):
path = request.get_full_path().replace("/", "_")[:100]
if sys.platform in ["win32", "cygwin"]:
path = path.replace("?", "_qs_")
default_filename = "{total_time:.3f}s {path} {timestamp:.0f}.{ext}"
return default_filename.format(
total_time=session.duration,
path=path,
timestamp=time.time(),
ext=renderer.output_file_extension,
)
filename_callback = default_filename_callback
filename = filename_callback(profile_session, request, renderer)
file_path = os.path.join(profile_dir, filename)
if not os.path.exists(profile_dir):
os.mkdir(profile_dir)
with open(file_path, "w", encoding="utf-8") as f:
f.write(output)
if getattr(settings, "PYINSTRUMENT_URL_ARGUMENT", "profile") in request.GET:
if isinstance(renderer, HTMLRenderer):
return HttpResponse(output) # type: ignore
else:
renderer = HTMLRenderer()
output = renderer.render(profile_session)
return HttpResponse(output) # type: ignore
else:
return response
else:
return response