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.

utils.py 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. from __future__ import absolute_import, unicode_literals
  2. import inspect
  3. import os.path
  4. import re
  5. import sys
  6. from importlib import import_module
  7. from itertools import chain
  8. import django
  9. from django.core.exceptions import ImproperlyConfigured
  10. from django.template import Node
  11. from django.utils import six
  12. from django.utils.encoding import force_text
  13. from django.utils.html import escape
  14. from django.utils.safestring import mark_safe
  15. from debug_toolbar import settings as dt_settings
  16. try:
  17. import threading
  18. except ImportError:
  19. threading = None
  20. # Figure out some paths
  21. django_path = os.path.realpath(os.path.dirname(django.__file__))
  22. def get_module_path(module_name):
  23. try:
  24. module = import_module(module_name)
  25. except ImportError as e:
  26. raise ImproperlyConfigured(
  27. 'Error importing HIDE_IN_STACKTRACES: %s' % (e,))
  28. else:
  29. source_path = inspect.getsourcefile(module)
  30. if source_path.endswith('__init__.py'):
  31. source_path = os.path.dirname(source_path)
  32. return os.path.realpath(source_path)
  33. hidden_paths = [
  34. get_module_path(module_name)
  35. for module_name in dt_settings.get_config()['HIDE_IN_STACKTRACES']
  36. ]
  37. def omit_path(path):
  38. return any(path.startswith(hidden_path) for hidden_path in hidden_paths)
  39. def tidy_stacktrace(stack):
  40. """
  41. Clean up stacktrace and remove all entries that:
  42. 1. Are part of Django (except contrib apps)
  43. 2. Are part of socketserver (used by Django's dev server)
  44. 3. Are the last entry (which is part of our stacktracing code)
  45. ``stack`` should be a list of frame tuples from ``inspect.stack()``
  46. """
  47. trace = []
  48. for frame, path, line_no, func_name, text in (f[:5] for f in stack):
  49. if omit_path(os.path.realpath(path)):
  50. continue
  51. text = (''.join(force_text(t) for t in text)).strip() if text else ''
  52. trace.append((path, line_no, func_name, text))
  53. return trace
  54. def render_stacktrace(trace):
  55. stacktrace = []
  56. for frame in trace:
  57. params = (escape(v) for v in chain(frame[0].rsplit(os.path.sep, 1), frame[1:]))
  58. params_dict = {six.text_type(idx): v for idx, v in enumerate(params)}
  59. try:
  60. stacktrace.append('<span class="djdt-path">%(0)s/</span>'
  61. '<span class="djdt-file">%(1)s</span>'
  62. ' in <span class="djdt-func">%(3)s</span>'
  63. '(<span class="djdt-lineno">%(2)s</span>)\n'
  64. ' <span class="djdt-code">%(4)s</span>'
  65. % params_dict)
  66. except KeyError:
  67. # This frame doesn't have the expected format, so skip it and move on to the next one
  68. continue
  69. return mark_safe('\n'.join(stacktrace))
  70. def get_template_info():
  71. template_info = None
  72. cur_frame = sys._getframe().f_back
  73. try:
  74. while cur_frame is not None:
  75. in_utils_module = cur_frame.f_code.co_filename.endswith(
  76. "/debug_toolbar/utils.py"
  77. )
  78. is_get_template_context = (
  79. cur_frame.f_code.co_name == get_template_context.__name__
  80. )
  81. if in_utils_module and is_get_template_context:
  82. # If the method in the stack trace is this one
  83. # then break from the loop as it's being check recursively.
  84. break
  85. elif cur_frame.f_code.co_name == 'render':
  86. node = cur_frame.f_locals['self']
  87. context = cur_frame.f_locals['context']
  88. if isinstance(node, Node):
  89. template_info = get_template_context(node, context)
  90. break
  91. cur_frame = cur_frame.f_back
  92. except Exception:
  93. pass
  94. del cur_frame
  95. return template_info
  96. def get_template_context(node, context, context_lines=3):
  97. line, source_lines, name = get_template_source_from_exception_info(
  98. node, context)
  99. debug_context = []
  100. start = max(1, line - context_lines)
  101. end = line + 1 + context_lines
  102. for line_num, content in source_lines:
  103. if start <= line_num <= end:
  104. debug_context.append({
  105. 'num': line_num,
  106. 'content': content,
  107. 'highlight': (line_num == line),
  108. })
  109. return {
  110. 'name': name,
  111. 'context': debug_context,
  112. }
  113. def get_template_source_from_exception_info(node, context):
  114. exception_info = context.template.get_exception_info(
  115. Exception('DDT'), node.token)
  116. line = exception_info['line']
  117. source_lines = exception_info['source_lines']
  118. name = exception_info['name']
  119. return line, source_lines, name
  120. def get_name_from_obj(obj):
  121. if hasattr(obj, '__name__'):
  122. name = obj.__name__
  123. elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
  124. name = obj.__class__.__name__
  125. else:
  126. name = '<unknown>'
  127. if hasattr(obj, '__module__'):
  128. module = obj.__module__
  129. name = '%s.%s' % (module, name)
  130. return name
  131. def getframeinfo(frame, context=1):
  132. """
  133. Get information about a frame or traceback object.
  134. A tuple of five things is returned: the filename, the line number of
  135. the current line, the function name, a list of lines of context from
  136. the source code, and the index of the current line within that list.
  137. The optional second argument specifies the number of lines of context
  138. to return, which are centered around the current line.
  139. This originally comes from ``inspect`` but is modified to handle issues
  140. with ``findsource()``.
  141. """
  142. if inspect.istraceback(frame):
  143. lineno = frame.tb_lineno
  144. frame = frame.tb_frame
  145. else:
  146. lineno = frame.f_lineno
  147. if not inspect.isframe(frame):
  148. raise TypeError('arg is not a frame or traceback object')
  149. filename = inspect.getsourcefile(frame) or inspect.getfile(frame)
  150. if context > 0:
  151. start = lineno - 1 - context // 2
  152. try:
  153. lines, lnum = inspect.findsource(frame)
  154. except Exception: # findsource raises platform-dependant exceptions
  155. first_lines = lines = index = None
  156. else:
  157. start = max(start, 1)
  158. start = max(0, min(start, len(lines) - context))
  159. first_lines = lines[:2]
  160. lines = lines[start:(start + context)]
  161. index = lineno - 1 - start
  162. else:
  163. first_lines = lines = index = None
  164. # Code taken from Django's ExceptionReporter._get_lines_from_file
  165. if first_lines and isinstance(first_lines[0], bytes):
  166. encoding = 'ascii'
  167. for line in first_lines[:2]:
  168. # File coding may be specified. Match pattern from PEP-263
  169. # (https://www.python.org/dev/peps/pep-0263/)
  170. match = re.search(br'coding[:=]\s*([-\w.]+)', line)
  171. if match:
  172. encoding = match.group(1).decode('ascii')
  173. break
  174. lines = [line.decode(encoding, 'replace') for line in lines]
  175. if hasattr(inspect, 'Traceback'):
  176. return inspect.Traceback(filename, lineno, frame.f_code.co_name, lines, index)
  177. else:
  178. return (filename, lineno, frame.f_code.co_name, lines, index)
  179. def get_stack(context=1):
  180. """
  181. Get a list of records for a frame and all higher (calling) frames.
  182. Each record contains a frame object, filename, line number, function
  183. name, a list of lines of context, and index within the context.
  184. Modified version of ``inspect.stack()`` which calls our own ``getframeinfo()``
  185. """
  186. frame = sys._getframe(1)
  187. framelist = []
  188. while frame:
  189. framelist.append((frame,) + getframeinfo(frame, context))
  190. frame = frame.f_back
  191. return framelist
  192. class ThreadCollector(object):
  193. def __init__(self):
  194. if threading is None:
  195. raise NotImplementedError(
  196. "threading module is not available, "
  197. "this panel cannot be used without it")
  198. self.collections = {} # a dictionary that maps threads to collections
  199. def get_collection(self, thread=None):
  200. """
  201. Returns a list of collected items for the provided thread, of if none
  202. is provided, returns a list for the current thread.
  203. """
  204. if thread is None:
  205. thread = threading.currentThread()
  206. if thread not in self.collections:
  207. self.collections[thread] = []
  208. return self.collections[thread]
  209. def clear_collection(self, thread=None):
  210. if thread is None:
  211. thread = threading.currentThread()
  212. if thread in self.collections:
  213. del self.collections[thread]
  214. def collect(self, item, thread=None):
  215. self.get_collection(thread).append(item)