import os.path from django.conf import settings from django.template import Template, Context from django.test.signals import template_rendered from django.test.utils import instrumented_test_render from django.utils.encoding import force_unicode TEMPLATE = """
""" # Monkeypatch instrumented test renderer from django.test.utils - we could use # django.test.utils.setup_test_environment for this but that would also set up # e-mail interception, which we don't want if Template.render != instrumented_test_render: Template.original_render = Template.render Template.render = instrumented_test_render # MONSTER monkey-patch old_template_init = Template.__init__ def new_template_init(self, template_string, origin=None, name=''): old_template_init(self, template_string, origin, name) self.origin = origin Template.__init__ = new_template_init class EditingMiddleware(object): link_format = "edit://%s?%s" def process_request(self, request): self.templates = [] template_rendered.connect(self.store_template) def process_view(self, request, view_func, view_args, view_kwargs): self.view_func = view_func self.view_args = view_args self.view_kwargs = view_kwargs def process_response(self, request, response): if not self.should_process_response(request, response): return response view_func = getattr(self, "view_func", None) if view_func is None: return response debug_content = self.get_template().render(self.get_context()) content = response.content response.content = force_unicode(content).replace('', debug_content) return response def get_template(self): return Template(TEMPLATE) def should_process_response(self, request, response): return 'text/html' in response['Content-Type'] def store_template(self, **kwargs): template = kwargs.get("template") if template is not None: self.templates.append(template) def get_context(self): templates = [ (self.build_link(os.path.join(settings.TEMPLATE_DIRS[0], t.name)), t.name) for t in self.templates ] view_link = self.build_link(self.view_func.func_code.co_filename, self.view_func.func_code.co_firstlineno) view_name = "%s.%s" % (self.view_func.__module__, self.view_func.func_name) return Context({ "view_link": view_link, "view_name": view_name, "templates": templates}) def build_link(self, filename, lineno=0): return self.link_format % (filename, lineno) class TextMateEditingMiddleware(EditingMiddleware): link_format = "txmt://open/?url=file://%s&line=%s"