Created
March 2, 2015 05:00
-
-
Save hirokiky/f7f12de9ec9cccd0d059 to your computer and use it in GitHub Desktop.
ProfileをするDjango middleware
This file contains hidden or 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
from io import StringIO | |
import cProfile | |
import pstats | |
from django.conf import settings | |
class ProfilerMiddleware(object): | |
""" プロファイラーを実行するMiddleware | |
プロファイル結果を見る場合は ``prof`` パラメータを追加してください: | |
http://127.0.0.1:8000/?prof | |
以下のパラメータも指定できます: | |
:?prof_sort: | |
アウトプットのテーブルをソートする。複数指定する場合は空白区切りで指定。 | |
ソートキーは以下のドキュメントを参照してください。 | |
http://docs.python.jp/2/library/profile.html#pstats.Stats.sort_stats | |
:?prof_count: | |
結果表示の行数 | |
以下のプレゼン資料から参考に実装 | |
http://www.slideshare.net/zeeg/django-con-high-performance-django-presentation | |
""" | |
def can(self, request): | |
return settings.DEBUG and 'prof' in request.GET | |
def process_request(self, request, *args, **kwargs): | |
if self.can(request): | |
self.profiler = cProfile.Profile() | |
self.profiler.enable() | |
def process_response(self, request, response): | |
if self.can(request): | |
self.profiler.disable() | |
self.profiler.create_stats() | |
io = StringIO() | |
stats = pstats.Stats(self.profiler, stream=io) | |
stats.strip_dirs().sort_stats(*request.GET.get('prof_sort', 'time').split(" ")) | |
stats.print_stats(int(request.GET.get('prof_count', 50))) | |
response.content = io.getvalue() | |
response["Content-Type"] = "text/plain" | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment