Skip to content

Instantly share code, notes, and snippets.

@float1251
Created May 5, 2014 11:41
Show Gist options
  • Save float1251/674ce959af32ef04e138 to your computer and use it in GitHub Desktop.
Save float1251/674ce959af32ef04e138 to your computer and use it in GitHub Desktop.
django-profile-middleware
from datetime import datetime
import cProfile
import pstats
from django.conf import settings
class PerfomanceMesuamentMiddleware:
"""
consoleに実行時間を表示する。
表示条件は以下
1. DEBUG=Trueとなっている
2. urlパラメータにprofileが定義されている
表示設定はurlパラメータに以下をつけると設定できる。
* detail: cProfileの結果を表示する
* count: cProfileの表示件数を設定する ex:100件表示する際はcount=100
"""
def process_request(self, request):
if self.enableProfile(request):
self.start_time = datetime.now()
return None
def process_view(self, request, view_func, view_args, view_kwargs):
if self.enableDetailProfile(request):
self.profile = cProfile.Profile()
args = (request,)+view_args
return self.profile.runcall(view_func, *args, **view_kwargs)
return None
def process_response(self, request, response):
if self.enableProfile(request):
time = datetime.now() - self.start_time
print("{0}: {1}sec".format(request.path_info, time.total_seconds()))
if self.enableDetailProfile(request):
stats = pstats.Stats(self.profile)
stats.strip_dirs().sort_stats(request.GET.get('sort', 'time'))
stats.print_stats(int(request.GET.get('count', 10)))
return response
def enableProfile(self, request):
if settings.DEBUG and "profile" in request.GET:
return True
return False
def enableDetailProfile(self, request):
if self.enableProfile(request) and "detail" in request.GET:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment