Skip to content

Commit

Permalink
Merge branch 'master' into patch-1
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel authored and Daniel committed Nov 8, 2018
1 parent 201a65b commit 78da08e
Show file tree
Hide file tree
Showing 65 changed files with 1,460 additions and 1,265 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Expand Up @@ -43,7 +43,8 @@ matrix:
addons:
postgresql: "9.5"
- env: TOXENV=flake8
- env: TOXENV=isort
- python: 3.6
env: TOXENV=style
- env: TOXENV=readme
allow_failures:
- env: TOXENV=py35-djmaster
Expand Down
13 changes: 8 additions & 5 deletions Makefile
@@ -1,13 +1,16 @@
.PHONY: flake8 example test coverage translatable_strings update_translations

flake8:
flake8 debug_toolbar example tests

isort:
style:
isort -rc debug_toolbar example tests
black debug_toolbar example tests setup.py
flake8 debug_toolbar example tests

isort_check_only:
style_check:
isort -rc -c debug_toolbar example tests
black --check debug_toolbar example tests setup.py

flake8:
flake8 debug_toolbar example tests

example:
python example/manage.py runserver
Expand Down
11 changes: 6 additions & 5 deletions debug_toolbar/__init__.py
@@ -1,17 +1,18 @@
from __future__ import absolute_import, unicode_literals

__all__ = ['VERSION']
__all__ = ["VERSION"]


try:
import pkg_resources
VERSION = pkg_resources.get_distribution('django-debug-toolbar').version

VERSION = pkg_resources.get_distribution("django-debug-toolbar").version
except Exception:
VERSION = 'unknown'
VERSION = "unknown"


# Code that discovers files or modules in INSTALLED_APPS imports this module.

urls = 'debug_toolbar.toolbar', 'djdt'
urls = "debug_toolbar.toolbar", "djdt"

default_app_config = 'debug_toolbar.apps.DebugToolbarConfig'
default_app_config = "debug_toolbar.apps.DebugToolbarConfig"
19 changes: 9 additions & 10 deletions debug_toolbar/apps.py
Expand Up @@ -11,7 +11,7 @@


class DebugToolbarConfig(AppConfig):
name = 'debug_toolbar'
name = "debug_toolbar"
verbose_name = _("Debug Toolbar")


Expand All @@ -23,11 +23,11 @@ def check_middleware(app_configs, **kwargs):
gzip_index = None
debug_toolbar_indexes = []

setting = getattr(settings, 'MIDDLEWARE', None)
setting_name = 'MIDDLEWARE'
setting = getattr(settings, "MIDDLEWARE", None)
setting_name = "MIDDLEWARE"
if setting is None:
setting = settings.MIDDLEWARE_CLASSES
setting_name = 'MIDDLEWARE_CLASSES'
setting_name = "MIDDLEWARE_CLASSES"

# Determine the indexes which gzip and/or the toolbar are installed at
for i, middleware in enumerate(setting):
Expand All @@ -44,7 +44,7 @@ def check_middleware(app_configs, **kwargs):
"from %s." % setting_name,
hint="Add debug_toolbar.middleware.DebugToolbarMiddleware to "
"%s." % setting_name,
id='debug_toolbar.W001',
id="debug_toolbar.W001",
)
)
elif len(debug_toolbar_indexes) != 1:
Expand All @@ -55,7 +55,7 @@ def check_middleware(app_configs, **kwargs):
"multiple times in %s." % setting_name,
hint="Load debug_toolbar.middleware.DebugToolbarMiddleware only "
"once in %s." % setting_name,
id='debug_toolbar.W002',
id="debug_toolbar.W002",
)
)
elif gzip_index is not None and debug_toolbar_indexes[0] < gzip_index:
Expand All @@ -66,7 +66,7 @@ def check_middleware(app_configs, **kwargs):
"django.middleware.gzip.GZipMiddleware in %s." % setting_name,
hint="Move debug_toolbar.middleware.DebugToolbarMiddleware to "
"after django.middleware.gzip.GZipMiddleware in %s." % setting_name,
id='debug_toolbar.W003',
id="debug_toolbar.W003",
)
)

Expand All @@ -78,7 +78,6 @@ def is_middleware_class(middleware_class, middleware_path):
middleware_cls = import_string(middleware_path)
except ImportError:
return
return (
inspect.isclass(middleware_cls) and
issubclass(middleware_cls, middleware_class)
return inspect.isclass(middleware_cls) and issubclass(
middleware_cls, middleware_class
)
1 change: 1 addition & 0 deletions debug_toolbar/decorators.py
Expand Up @@ -13,4 +13,5 @@ def inner(request, *args, **kwargs):
raise Http404

return view(request, *args, **kwargs)

return inner
5 changes: 3 additions & 2 deletions debug_toolbar/management/commands/debugsqlshell.py
Expand Up @@ -3,10 +3,11 @@
from time import time

import sqlparse
# 'debugsqlshell' is the same as the 'shell'.
from django.core.management.commands.shell import Command # noqa
from django.db.backends import utils as db_backends_utils

# 'debugsqlshell' is the same as the 'shell'.


class PrintQueryWrapper(db_backends_utils.CursorDebugWrapper):
def execute(self, sql, params=()):
Expand All @@ -18,7 +19,7 @@ def execute(self, sql, params=()):
end_time = time()
duration = (end_time - start_time) * 1000
formatted_sql = sqlparse.format(raw_sql, reindent=True)
print('%s [%.2fms]' % (formatted_sql, duration))
print("%s [%.2fms]" % (formatted_sql, duration))


db_backends_utils.CursorDebugWrapper = PrintQueryWrapper
50 changes: 30 additions & 20 deletions debug_toolbar/middleware.py
Expand Up @@ -17,14 +17,14 @@
from debug_toolbar import settings as dt_settings
from debug_toolbar.toolbar import DebugToolbar

_HTML_TYPES = ('text/html', 'application/xhtml+xml')
_HTML_TYPES = ("text/html", "application/xhtml+xml")


def show_toolbar(request):
"""
Default function to determine whether to show the toolbar on a given page.
"""
if request.META.get('REMOTE_ADDR', None) not in settings.INTERNAL_IPS:
if request.META.get("REMOTE_ADDR", None) not in settings.INTERNAL_IPS:
return False

return bool(settings.DEBUG)
Expand All @@ -34,7 +34,7 @@ def show_toolbar(request):
def get_show_toolbar():
# If SHOW_TOOLBAR_CALLBACK is a string, which is the recommended
# setup, resolve it to the corresponding callable.
func_or_path = dt_settings.get_config()['SHOW_TOOLBAR_CALLBACK']
func_or_path = dt_settings.get_config()["SHOW_TOOLBAR_CALLBACK"]
if isinstance(func_or_path, six.string_types):
return import_string(func_or_path)
else:
Expand All @@ -46,6 +46,7 @@ class DebugToolbarMiddleware(MiddlewareMixin):
Middleware to set up Debug Toolbar on incoming request and render toolbar
on outgoing response.
"""

debug_toolbars = {}

def process_request(self, request):
Expand Down Expand Up @@ -87,7 +88,9 @@ def process_view(self, request, view_func, view_args, view_kwargs):
return response

def process_response(self, request, response):
toolbar = self.__class__.debug_toolbars.pop(threading.current_thread().ident, None)
toolbar = self.__class__.debug_toolbars.pop(
threading.current_thread().ident, None
)
if not toolbar:
return response

Expand All @@ -104,20 +107,24 @@ def process_response(self, request, response):
panel.disable_instrumentation()

# Check for responses where the toolbar can't be inserted.
content_encoding = response.get('Content-Encoding', '')
content_type = response.get('Content-Type', '').split(';')[0]
if any((getattr(response, 'streaming', False),
'gzip' in content_encoding,
content_type not in _HTML_TYPES)):
content_encoding = response.get("Content-Encoding", "")
content_type = response.get("Content-Type", "").split(";")[0]
if any(
(
getattr(response, "streaming", False),
"gzip" in content_encoding,
content_type not in _HTML_TYPES,
)
):
return response

# Collapse the toolbar by default if SHOW_COLLAPSED is set.
if toolbar.config['SHOW_COLLAPSED'] and 'djdt' not in request.COOKIES:
response.set_cookie('djdt', 'hide', 864000)
if toolbar.config["SHOW_COLLAPSED"] and "djdt" not in request.COOKIES:
response.set_cookie("djdt", "hide", 864000)

# Insert the toolbar in the response.
content = force_text(response.content, encoding=response.charset)
insert_before = dt_settings.get_config()['INSERT_BEFORE']
insert_before = dt_settings.get_config()["INSERT_BEFORE"]
pattern = re.escape(insert_before)
bits = re.split(pattern, content, flags=re.IGNORECASE)
if len(bits) > 1:
Expand All @@ -126,12 +133,14 @@ def process_response(self, request, response):
panel.generate_stats(request, response)
panel.generate_server_timing(request, response)

response = self.generate_server_timing_header(response, toolbar.enabled_panels)
response = self.generate_server_timing_header(
response, toolbar.enabled_panels
)

bits[-2] += toolbar.render_toolbar()
response.content = insert_before.join(bits)
if response.get('Content-Length', None):
response['Content-Length'] = len(response.content)
if response.get("Content-Length", None):
response["Content-Length"] = len(response.content)
return response

@staticmethod
Expand All @@ -145,11 +154,12 @@ def generate_server_timing_header(response, panels):

for key, record in stats.items():
# example: `SQLPanel_sql_time=0; "SQL 0 queries"`
data.append('{}_{}={}; "{}"'.format(panel.panel_id,
key,
record.get('value'),
record.get('title')))
data.append(
'{}_{}={}; "{}"'.format(
panel.panel_id, key, record.get("value"), record.get("title")
)
)

if data:
response['Server-Timing'] = ', '.join(data)
response["Server-Timing"] = ", ".join(data)
return response
17 changes: 9 additions & 8 deletions debug_toolbar/panels/__init__.py
Expand Up @@ -12,6 +12,7 @@ class Panel(object):
"""
Base class for panels.
"""

def __init__(self, toolbar):
self.toolbar = toolbar

Expand All @@ -24,21 +25,22 @@ def panel_id(self):
@property
def enabled(self):
# Check to see if settings has a default value for it
disabled_panels = dt_settings.get_config()['DISABLE_PANELS']
disabled_panels = dt_settings.get_config()["DISABLE_PANELS"]
panel_path = get_name_from_obj(self)
# Some panels such as the SQLPanel and TemplatesPanel exist in a
# panel module, but can be disabled without panel in the path.
# For that reason, replace .panel. in the path and check for that
# value in the disabled panels as well.
disable_panel = (
panel_path in disabled_panels or
panel_path.replace('.panel.', '.') in disabled_panels)
panel_path in disabled_panels
or panel_path.replace(".panel.", ".") in disabled_panels
)
if disable_panel:
default = 'off'
default = "off"
else:
default = 'on'
default = "on"
# The user's cookies should override the default value
return self.toolbar.request.COOKIES.get('djdt' + self.panel_id, default) == 'on'
return self.toolbar.request.COOKIES.get("djdt" + self.panel_id, default) == "on"

# Titles and content

Expand All @@ -54,7 +56,7 @@ def nav_subtitle(self):
"""
Subtitle shown in the side bar. Defaults to the empty string.
"""
return ''
return ""

@property
def has_content(self):
Expand Down Expand Up @@ -220,7 +222,6 @@ def generate_server_timing(self, request, response):

# Backward-compatibility for 1.0, remove in 2.0.
class DebugPanel(Panel):

def __init__(self, *args, **kwargs):
warnings.warn("DebugPanel was renamed to Panel.", DeprecationWarning)
super(DebugPanel, self).__init__(*args, **kwargs)

0 comments on commit 78da08e

Please sign in to comment.