Skip to content

Instantly share code, notes, and snippets.

@LeonardoGentile
Created April 21, 2015 15:52
Show Gist options
  • Save LeonardoGentile/2fba5dc0adeda101a696 to your computer and use it in GitHub Desktop.
Save LeonardoGentile/2fba5dc0adeda101a696 to your computer and use it in GitHub Desktop.
PyCallGraph Middleware for python
1. Replace myapp in the snippet with the name of your application and or adjust include and exclude according to your needs
2. Add CallgraphMiddleware to your middlewares in settings.py
3. Append ?graph to any URL in your application to trigger the callgraph creation
4. Each callgraph cerated will be named callgraph-timestamp.png. This is because multiple callgraphs will be created when a re-direction occurs for example.
Credits:
- https://djangosnippets.org/snippets/1316/
import time
from django.conf import settings
from pycallgraph import Config
from pycallgraph import PyCallGraph
from pycallgraph import GlobbingFilter
from pycallgraph.output import GraphvizOutput
class CallgraphMiddleware(object):
def process_view(self, request, callback, callback_args, callback_kwargs):
if settings.DEBUG and 'graph' in request.GET:
config = Config()
config.trace_filter = GlobbingFilter(include=['myapp.*'], exclude=['myapp.debug*','*.secret_function',] )
graphviz = GraphvizOutput(output_file='callgraph-' + str(time.time()) + '.png')
pycallgraph = PyCallGraph(output=graphviz, config=config)
pycallgraph.start()
self.pycallgraph = pycallgraph
def process_response(self, request, response):
if settings.DEBUG and 'graph' in request.GET:
self.pycallgraph.done()
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment