PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/build/django-debug-toolbar/debug_toolbar/middleware.py

https://bitbucket.org/code4ghana/liquorfox
Python | 137 lines | 99 code | 24 blank | 14 comment | 22 complexity | fa4f8a017cfa74690233b8049dce295d MD5 | raw file
  1. """
  2. Debug Toolbar middleware
  3. """
  4. import imp
  5. import thread
  6. from django.conf import settings
  7. from django.http import HttpResponseRedirect
  8. from django.shortcuts import render_to_response
  9. from django.utils.encoding import smart_unicode
  10. from django.utils.importlib import import_module
  11. import debug_toolbar.urls
  12. from debug_toolbar.toolbar.loader import DebugToolbar
  13. _HTML_TYPES = ('text/html', 'application/xhtml+xml')
  14. def replace_insensitive(string, target, replacement):
  15. """
  16. Similar to string.replace() but is case insensitive
  17. Code borrowed from: http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html
  18. """
  19. no_case = string.lower()
  20. index = no_case.rfind(target.lower())
  21. if index >= 0:
  22. return string[:index] + replacement + string[index + len(target):]
  23. else: # no results so return the original string
  24. return string
  25. class DebugToolbarMiddleware(object):
  26. """
  27. Middleware to set up Debug Toolbar on incoming request and render toolbar
  28. on outgoing response.
  29. """
  30. debug_toolbars = {}
  31. @classmethod
  32. def get_current(cls):
  33. return cls.debug_toolbars.get(thread.get_ident())
  34. def __init__(self):
  35. self._urlconfs = {}
  36. # Set method to use to decide to show toolbar
  37. self.show_toolbar = self._show_toolbar # default
  38. # The tag to attach the toolbar to
  39. self.tag = u'</body>'
  40. if hasattr(settings, 'DEBUG_TOOLBAR_CONFIG'):
  41. show_toolbar_callback = settings.DEBUG_TOOLBAR_CONFIG.get(
  42. 'SHOW_TOOLBAR_CALLBACK', None)
  43. if show_toolbar_callback:
  44. self.show_toolbar = show_toolbar_callback
  45. tag = settings.DEBUG_TOOLBAR_CONFIG.get('TAG', None)
  46. if tag:
  47. self.tag = u'</' + tag + u'>'
  48. def _show_toolbar(self, request):
  49. if getattr(settings, 'TEST', False):
  50. return False
  51. x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None)
  52. if x_forwarded_for:
  53. remote_addr = x_forwarded_for.split(',')[0].strip()
  54. else:
  55. remote_addr = request.META.get('REMOTE_ADDR', None)
  56. # if not internal ip, and not DEBUG
  57. return remote_addr in settings.INTERNAL_IPS and bool(settings.DEBUG)
  58. def process_request(self, request):
  59. __traceback_hide__ = True
  60. if self.show_toolbar(request):
  61. urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
  62. if isinstance(urlconf, basestring):
  63. urlconf = import_module(getattr(request, 'urlconf', settings.ROOT_URLCONF))
  64. if urlconf not in self._urlconfs:
  65. new_urlconf = imp.new_module('urlconf')
  66. new_urlconf.urlpatterns = debug_toolbar.urls.urlpatterns + \
  67. urlconf.urlpatterns
  68. if hasattr(urlconf, 'handler404'):
  69. new_urlconf.handler404 = urlconf.handler404
  70. if hasattr(urlconf, 'handler500'):
  71. new_urlconf.handler500 = urlconf.handler500
  72. self._urlconfs[urlconf] = new_urlconf
  73. request.urlconf = self._urlconfs[urlconf]
  74. toolbar = DebugToolbar(request)
  75. for panel in toolbar.panels:
  76. panel.process_request(request)
  77. self.__class__.debug_toolbars[thread.get_ident()] = toolbar
  78. def process_view(self, request, view_func, view_args, view_kwargs):
  79. __traceback_hide__ = True
  80. toolbar = self.__class__.debug_toolbars.get(thread.get_ident())
  81. if not toolbar:
  82. return
  83. for panel in toolbar.panels:
  84. panel.process_view(request, view_func, view_args, view_kwargs)
  85. def process_response(self, request, response):
  86. __traceback_hide__ = True
  87. ident = thread.get_ident()
  88. toolbar = self.__class__.debug_toolbars.get(ident)
  89. if not toolbar:
  90. return response
  91. if isinstance(response, HttpResponseRedirect):
  92. if not toolbar.config['INTERCEPT_REDIRECTS']:
  93. return response
  94. redirect_to = response.get('Location', None)
  95. if redirect_to:
  96. cookies = response.cookies
  97. response = render_to_response(
  98. 'debug_toolbar/redirect.html',
  99. {'redirect_to': redirect_to}
  100. )
  101. response.cookies = cookies
  102. if 'gzip' not in response.get('Content-Encoding', '') and \
  103. response.get('Content-Type', '').split(';')[0] in _HTML_TYPES:
  104. for panel in toolbar.panels:
  105. panel.process_response(request, response)
  106. response.content = replace_insensitive(
  107. smart_unicode(response.content),
  108. self.tag,
  109. smart_unicode(toolbar.render_toolbar() + self.tag))
  110. if response.get('Content-Length', None):
  111. response['Content-Length'] = len(response.content)
  112. del self.__class__.debug_toolbars[ident]
  113. return response