Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

panel.py 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from __future__ import absolute_import, unicode_literals
  2. from collections import OrderedDict
  3. from contextlib import contextmanager
  4. from os.path import normpath
  5. from pprint import pformat, saferepr
  6. from django import http
  7. from django.conf.urls import url
  8. from django.core import signing
  9. from django.db.models.query import QuerySet, RawQuerySet
  10. from django.template import RequestContext, Template
  11. from django.test.signals import template_rendered
  12. from django.test.utils import instrumented_test_render
  13. from django.utils import six
  14. from django.utils.encoding import force_text
  15. from django.utils.translation import ugettext_lazy as _
  16. from debug_toolbar.panels import Panel
  17. from debug_toolbar.panels.sql.tracking import SQLQueryTriggered, recording
  18. from debug_toolbar.panels.templates import views
  19. # Monkey-patch to enable the template_rendered signal. The receiver returns
  20. # immediately when the panel is disabled to keep the overhead small.
  21. # Code taken and adapted from Simon Willison and Django Snippets:
  22. # https://www.djangosnippets.org/snippets/766/
  23. if Template._render != instrumented_test_render:
  24. Template.original_render = Template._render
  25. Template._render = instrumented_test_render
  26. # Monkey-patch to store items added by template context processors. The
  27. # overhead is sufficiently small to justify enabling it unconditionally.
  28. @contextmanager
  29. def _request_context_bind_template(self, template):
  30. if self.template is not None:
  31. raise RuntimeError("Context is already bound to a template")
  32. self.template = template
  33. # Set context processors according to the template engine's settings.
  34. processors = (template.engine.template_context_processors +
  35. self._processors)
  36. self.context_processors = OrderedDict()
  37. updates = {}
  38. for processor in processors:
  39. name = '%s.%s' % (processor.__module__, processor.__name__)
  40. context = processor(self.request)
  41. self.context_processors[name] = context
  42. updates.update(context)
  43. self.dicts[self._processors_index] = updates
  44. try:
  45. yield
  46. finally:
  47. self.template = None
  48. # Unset context processors.
  49. self.dicts[self._processors_index] = {}
  50. RequestContext.bind_template = _request_context_bind_template
  51. class TemplatesPanel(Panel):
  52. """
  53. A panel that lists all templates used during processing of a response.
  54. """
  55. def __init__(self, *args, **kwargs):
  56. super(TemplatesPanel, self).__init__(*args, **kwargs)
  57. self.templates = []
  58. # Refs GitHub issue #910
  59. # Hold a series of seen dictionaries within Contexts. A dictionary is
  60. # considered seen if it is `in` this list, requiring that the __eq__
  61. # for the dictionary matches. If *anything* in the dictionary is
  62. # different it is counted as a new layer.
  63. self.seen_layers = []
  64. # Holds all dictionaries which have been prettified for output.
  65. # This should align with the seen_layers such that an index here is
  66. # the same as the index there.
  67. self.pformat_layers = []
  68. def _store_template_info(self, sender, **kwargs):
  69. template, context = kwargs['template'], kwargs['context']
  70. # Skip templates that we are generating through the debug toolbar.
  71. if (isinstance(template.name, six.string_types) and (
  72. template.name.startswith('debug_toolbar/') or
  73. template.name.startswith(
  74. tuple(self.toolbar.config['SKIP_TEMPLATE_PREFIXES'])))):
  75. return
  76. context_list = []
  77. for context_layer in context.dicts:
  78. if hasattr(context_layer, 'items') and context_layer:
  79. # Refs GitHub issue #910
  80. # If we can find this layer in our pseudo-cache then find the
  81. # matching prettified version in the associated list.
  82. key_values = sorted(context_layer.items())
  83. if key_values in self.seen_layers:
  84. index = self.seen_layers.index(key_values)
  85. pformatted = self.pformat_layers[index]
  86. context_list.append(pformatted)
  87. else:
  88. temp_layer = {}
  89. for key, value in context_layer.items():
  90. # Replace any request elements - they have a large
  91. # unicode representation and the request data is
  92. # already made available from the Request panel.
  93. if isinstance(value, http.HttpRequest):
  94. temp_layer[key] = '<<request>>'
  95. # Replace the debugging sql_queries element. The SQL
  96. # data is already made available from the SQL panel.
  97. elif key == 'sql_queries' and isinstance(value, list):
  98. temp_layer[key] = '<<sql_queries>>'
  99. # Replace LANGUAGES, which is available in i18n context processor
  100. elif key == 'LANGUAGES' and isinstance(value, tuple):
  101. temp_layer[key] = '<<languages>>'
  102. # QuerySet would trigger the database: user can run the query from SQL Panel
  103. elif isinstance(value, (QuerySet, RawQuerySet)):
  104. model_name = "%s.%s" % (
  105. value.model._meta.app_label, value.model.__name__)
  106. temp_layer[key] = '<<%s of %s>>' % (
  107. value.__class__.__name__.lower(), model_name)
  108. else:
  109. try:
  110. recording(False)
  111. saferepr(value) # this MAY trigger a db query
  112. except SQLQueryTriggered:
  113. temp_layer[key] = '<<triggers database query>>'
  114. except UnicodeEncodeError:
  115. temp_layer[key] = '<<unicode encode error>>'
  116. except Exception:
  117. temp_layer[key] = '<<unhandled exception>>'
  118. else:
  119. temp_layer[key] = value
  120. finally:
  121. recording(True)
  122. # Refs GitHub issue #910
  123. # If we've not seen the layer before then we will add it
  124. # so that if we see it again we can skip formatting it.
  125. self.seen_layers.append(key_values)
  126. # Note: this *ought* to be len(...) - 1 but let's be safe.
  127. index = self.seen_layers.index(key_values)
  128. try:
  129. pformatted = force_text(pformat(temp_layer))
  130. except UnicodeEncodeError:
  131. pass
  132. else:
  133. # Note: this *ought* to be len(...) - 1 but let's be safe.
  134. self.pformat_layers.insert(index, pformatted)
  135. context_list.append(pformatted)
  136. kwargs['context'] = context_list
  137. kwargs['context_processors'] = getattr(context, 'context_processors', None)
  138. self.templates.append(kwargs)
  139. # Implement the Panel API
  140. nav_title = _("Templates")
  141. @property
  142. def title(self):
  143. num_templates = len(self.templates)
  144. return _("Templates (%(num_templates)s rendered)") % {'num_templates': num_templates}
  145. @property
  146. def nav_subtitle(self):
  147. if self.templates:
  148. return self.templates[0]['template'].name
  149. return ''
  150. template = 'debug_toolbar/panels/templates.html'
  151. @classmethod
  152. def get_urls(cls):
  153. return [
  154. url(r'^template_source/$', views.template_source, name='template_source'),
  155. ]
  156. def enable_instrumentation(self):
  157. template_rendered.connect(self._store_template_info)
  158. def disable_instrumentation(self):
  159. template_rendered.disconnect(self._store_template_info)
  160. def generate_stats(self, request, response):
  161. template_context = []
  162. for template_data in self.templates:
  163. info = {}
  164. # Clean up some info about templates
  165. template = template_data.get('template', None)
  166. if hasattr(template, 'origin') and template.origin and template.origin.name:
  167. template.origin_name = template.origin.name
  168. template.origin_hash = signing.dumps(template.origin.name)
  169. else:
  170. template.origin_name = _('No origin')
  171. template.origin_hash = ''
  172. info['template'] = template
  173. # Clean up context for better readability
  174. if self.toolbar.config['SHOW_TEMPLATE_CONTEXT']:
  175. context_list = template_data.get('context', [])
  176. info['context'] = '\n'.join(context_list)
  177. template_context.append(info)
  178. # Fetch context_processors/template_dirs from any template
  179. if self.templates:
  180. context_processors = self.templates[0]['context_processors']
  181. template = self.templates[0]['template']
  182. # django templates have the 'engine' attribute, while jinja templates use 'backend'
  183. engine_backend = getattr(template, 'engine', None) or getattr(template, 'backend')
  184. template_dirs = engine_backend.dirs
  185. else:
  186. context_processors = None
  187. template_dirs = []
  188. self.record_stats({
  189. 'templates': template_context,
  190. 'template_dirs': [normpath(x) for x in template_dirs],
  191. 'context_processors': context_processors,
  192. })