1

I'm trying to implement a middleware in django(1.4) to create a call graph using PyCallGraph. I've based it from two different snippets found online. This is what it looks like:

import time
from django.conf import settings
from pycallgraph import Config
from pycallgraph import PyCallGraph
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(exclude=['pycallgraph.*','*.secret_function',], include=['reports.*'])
            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

I've added it to the other middlewares installed on settings.py then started the server.
It seems to trigger when the process_view is called but when it gets to process_response django complains, telling me that 'CallgraphMiddleware' object has no attribute 'pycallgraph'. How is that possible? Apparently the line

self.pycallgraph = pycallgraph

is not taken into account. Why?

Leonardo
  • 4,046
  • 5
  • 44
  • 85
  • 1
    There are situations where `process_response()` is called, but `process_view()` isn't, e.g. when request middleware, or view middleware that's executed before your own middleware, returns a valid `HttpResonse`. Can you check if `process_view()` is actually run? – knbk Apr 21 '15 at 15:23
  • @knbk yes it is. I've also double checked if the instance of `CallgraphMiddleware` is the same when calling `process_view` and `process_response` and yes it is! So, no idea.. – Leonardo Apr 21 '15 at 15:26

1 Answers1

1

I did forget to import GlobbingFilter so I had an exception that wouldn't let the code run up to the line self.pycallgraph = pycallgraph

Also PyCharm was not properly configured. I solved thank to this Answer:
https://stackoverflow.com/a/20335280/1191416

Community
  • 1
  • 1
Leonardo
  • 4,046
  • 5
  • 44
  • 85