Skip to content

Support for Python 3 #412

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@ language: python
python:
- "2.6"
- "2.7"
- "3.2"
- "3.3"
env:
- DJANGO_VERSION=1.3.7
- DJANGO_VERSION=1.4.5
- DJANGO_VERSION=1.5.1
- DJANGO_VERSION=1.4.8
- DJANGO_VERSION=1.5.4
matrix:
exclude:
- python: "3.2"
env: DJANGO_VERSION=1.4.8
- python: "3.3"
env: DJANGO_VERSION=1.4.8
install:
- pip install Django==$DJANGO_VERSION
script: python setup.py test
9 changes: 8 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,14 @@ There is also one Django management command currently:

If you have ideas for other panels please let us know.

* Note: The Debug Toolbar only works on Django 1.3 and newer.
Requirements
============

The current version of the Debug Toolbar is 0.9.4. It works on Django 1.3 and
1.4.

The next version will work on Django 1.4 (1.4.2 or later) and 1.5. In
addition, it will require Python 2.6 or later.

Installation
============
Expand Down
4 changes: 3 additions & 1 deletion debug_toolbar/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from __future__ import unicode_literals

__all__ = ('VERSION',)

try:
VERSION = __import__('pkg_resources') \
.get_distribution('django-debug-toolbar').version
except Exception, e:
except Exception as e:
VERSION = 'unknown'
24 changes: 9 additions & 15 deletions debug_toolbar/forms.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
from __future__ import unicode_literals

import json
import hashlib

from django import forms
from django.conf import settings
from django.utils.encoding import smart_str
from django.db import connections
from django.utils.encoding import smart_bytes
from django.utils.functional import cached_property
from django.core.exceptions import ValidationError

from debug_toolbar.utils.functional import cached_property
from debug_toolbar.utils.sql import reformat_sql

try:
import json
except ImportError:
from django.utils import simplejson as json

try:
from hashlib import sha1
except ImportError:
from django.utils.hashcompat import sha_constructor as sha1

from debug_toolbar.utils.compat.db import connections


class SQLSelectForm(forms.Form):
"""
Expand Down Expand Up @@ -83,7 +77,7 @@ def reformat_sql(self):

def make_hash(self, data):
params = settings.SECRET_KEY + data['sql'] + data['params']
return sha1(smart_str(params)).hexdigest()
return hashlib.sha1(smart_bytes(params)).hexdigest()

@property
def connection(self):
Expand Down
15 changes: 9 additions & 6 deletions debug_toolbar/management/commands/debugsqlshell.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from __future__ import print_function, unicode_literals

from datetime import datetime

from django.db.backends import util
from django.core.management.commands.shell import Command

from debug_toolbar.utils import ms_from_timedelta, sqlparse
import sqlparse

from debug_toolbar.utils import ms_from_timedelta


class PrintQueryWrapper(util.CursorDebugWrapper):
Expand All @@ -13,9 +16,9 @@ def execute(self, sql, params=()):
return self.cursor.execute(sql, params)
finally:
raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params)
execution_time = datetime.now() - starttime
print sqlparse.format(raw_sql, reindent=True),
print ' [%.2fms]' % (ms_from_timedelta(execution_time),)
print
execution_time = ms_from_timedelta(datetime.now() - starttime)
formatted_sql = sqlparse.format(raw_sql, reindent=True)
print('%s [%.2fms]' % (formatted_sql, execution_time))


util.CursorDebugWrapper = PrintQueryWrapper
24 changes: 14 additions & 10 deletions debug_toolbar/middleware.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
"""
Debug Toolbar middleware
"""

from __future__ import unicode_literals

import imp
import threading

from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.utils.encoding import smart_unicode
from django.utils.encoding import force_text
from django.utils.importlib import import_module
from django.utils import six

import debug_toolbar.urls
from debug_toolbar.toolbar.loader import DebugToolbar
Expand Down Expand Up @@ -39,7 +43,7 @@ class DebugToolbarMiddleware(object):

@classmethod
def get_current(cls):
return cls.debug_toolbars.get(threading.currentThread().ident)
return cls.debug_toolbars.get(threading.current_thread().ident)

def __init__(self):
self._urlconfs = {}
Expand All @@ -48,7 +52,7 @@ def __init__(self):
self.show_toolbar = self._show_toolbar # default

# The tag to attach the toolbar to
self.tag = u'</body>'
self.tag = '</body>'

if hasattr(settings, 'DEBUG_TOOLBAR_CONFIG'):
show_toolbar_callback = settings.DEBUG_TOOLBAR_CONFIG.get(
Expand All @@ -58,7 +62,7 @@ def __init__(self):

tag = settings.DEBUG_TOOLBAR_CONFIG.get('TAG', None)
if tag:
self.tag = u'</' + tag + u'>'
self.tag = '</' + tag + '>'

def _show_toolbar(self, request):
if getattr(settings, 'TEST', False):
Expand All @@ -77,7 +81,7 @@ def process_request(self, request):
__traceback_hide__ = True
if self.show_toolbar(request):
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, basestring):
if isinstance(urlconf, six.string_types):
urlconf = import_module(getattr(request, 'urlconf', settings.ROOT_URLCONF))

if urlconf not in self._urlconfs:
Expand All @@ -99,11 +103,11 @@ def process_request(self, request):
toolbar = DebugToolbar(request)
for panel in toolbar.panels:
panel.process_request(request)
self.__class__.debug_toolbars[threading.currentThread().ident] = toolbar
self.__class__.debug_toolbars[threading.current_thread().ident] = toolbar

def process_view(self, request, view_func, view_args, view_kwargs):
__traceback_hide__ = True
toolbar = self.__class__.debug_toolbars.get(threading.currentThread().ident)
toolbar = self.__class__.debug_toolbars.get(threading.current_thread().ident)
if not toolbar:
return
result = None
Expand All @@ -115,7 +119,7 @@ def process_view(self, request, view_func, view_args, view_kwargs):

def process_response(self, request, response):
__traceback_hide__ = True
ident = threading.currentThread().ident
ident = threading.current_thread().ident
toolbar = self.__class__.debug_toolbars.get(ident)
if not toolbar or request.is_ajax() or getattr(response, 'streaming', False):
return response
Expand All @@ -135,9 +139,9 @@ def process_response(self, request, response):
for panel in toolbar.panels:
panel.process_response(request, response)
response.content = replace_insensitive(
smart_unicode(response.content),
force_text(response.content),
self.tag,
smart_unicode(toolbar.render_toolbar() + self.tag))
force_text(toolbar.render_toolbar() + self.tag))
if response.get('Content-Length', None):
response['Content-Length'] = len(response.content)
del self.__class__.debug_toolbars[ident]
Expand Down
2 changes: 2 additions & 0 deletions debug_toolbar/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.conf import settings
from django.utils.importlib import import_module

Expand Down
2 changes: 2 additions & 0 deletions debug_toolbar/panels/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.template.defaultfilters import slugify
from django.template.loader import render_to_string
from debug_toolbar.middleware import DebugToolbarMiddleware
Expand Down
8 changes: 5 additions & 3 deletions debug_toolbar/panels/cache.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

import inspect
import sys
import time
Expand Down Expand Up @@ -42,7 +44,7 @@ def wrapped(self, *args, **kwargs):
template_info = get_template_info(node.source)
break
cur_frame = cur_frame.f_back
except:
except Exception:
pass
del cur_frame
cache_called.send(sender=self.__class__, time_taken=t,
Expand All @@ -59,7 +61,7 @@ def __init__(self, cache):
self.cache = cache

def __repr__(self):
return u"<CacheStatTracker for %s>" % self.cache.__repr__()
return str("<CacheStatTracker for %s>") % repr(self.cache)

def _get_func_info(self):
frame = sys._getframe(3)
Expand Down Expand Up @@ -166,7 +168,7 @@ def _store_call_info(self, sender, name=None, time_taken=0,
else:
self.hits += 1
elif name == 'get_many':
for key, value in return_value.iteritems():
for key, value in return_value.items():
if value is None:
self.misses += 1
else:
Expand Down
2 changes: 2 additions & 0 deletions debug_toolbar/panels/headers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.utils.translation import ugettext_lazy as _
from debug_toolbar.panels import DebugPanel

Expand Down
2 changes: 2 additions & 0 deletions debug_toolbar/panels/logger.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

import datetime
import logging
try:
Expand Down
18 changes: 9 additions & 9 deletions debug_toolbar/panels/profiling.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import division
from __future__ import division, unicode_literals

from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.utils.six.moves import cStringIO
from debug_toolbar.panels import DebugPanel

try:
Expand All @@ -11,7 +12,6 @@
DJ_PROFILE_USE_LINE_PROFILER = False


from cStringIO import StringIO
import cProfile
from pstats import Stats
from colorsys import hsv_to_rgb
Expand All @@ -23,7 +23,7 @@ class DjangoDebugToolbarStats(Stats):

def get_root_func(self):
if self.__root is None:
for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
for func, (cc, nc, tt, ct, callers) in self.stats.items():
if len(callers) == 0:
self.__root = func
break
Expand Down Expand Up @@ -80,7 +80,7 @@ def subfuncs(self):
i = 0
h, s, v = self.hsv
count = len(self.statobj.all_callees[self.func])
for func, stats in self.statobj.all_callees[self.func].iteritems():
for func, stats in self.statobj.all_callees[self.func].items():
i += 1
h1 = h + (i / count) / (self.depth + 1)
if stats[3] == 0:
Expand Down Expand Up @@ -128,7 +128,7 @@ def line_stats_text(self):
if self._line_stats_text is None and DJ_PROFILE_USE_LINE_PROFILER:
lstats = self.statobj.line_stats
if self.func in lstats.timings:
out = StringIO()
out = cStringIO.StringIO()
fn, lineno, name = self.func
show_func(fn, lineno, name, lstats.timings[self.func], lstats.unit, stream=out)
self._line_stats_text = out.getvalue()
Expand All @@ -155,12 +155,12 @@ def title(self):
return _('Profiling')

def _unwrap_closure_and_profile(self, func):
if not hasattr(func, 'func_code'):
if not hasattr(func, '__code__'):
return
self.line_profiler.add_function(func)
if func.func_closure:
for cell in func.func_closure:
if hasattr(cell.cell_contents, 'func_code'):
if func.__closure__:
for cell in func.__closure__:
if hasattr(cell.cell_contents, '__code__'):
self._unwrap_closure_and_profile(cell.cell_contents)

def process_view(self, request, view_func, view_args, view_kwargs):
Expand Down
4 changes: 3 additions & 1 deletion debug_toolbar/panels/request_vars.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.core.urlresolvers import resolve
from django.http import Http404
from django.utils.translation import ugettext_lazy as _
Expand Down Expand Up @@ -53,5 +55,5 @@ def process_response(self, request, response):
if hasattr(self.request, 'session'):
self.record_stats({
'session': [(k, self.request.session.get(k))
for k in self.request.session.iterkeys()]
for k in self.request.session.keys()]
})
2 changes: 2 additions & 0 deletions debug_toolbar/panels/settings_vars.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.conf import settings
from django.views.debug import get_safe_settings
from django.utils.translation import ugettext_lazy as _
Expand Down
8 changes: 5 additions & 3 deletions debug_toolbar/panels/signals.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

from django.conf import settings
from django.core.signals import (request_started, request_finished,
got_request_exception)
Expand Down Expand Up @@ -87,9 +89,9 @@ def process_response(self, request, response):

receiver = getattr(receiver, '__wraps__', receiver)
receiver_name = getattr(receiver, '__name__', str(receiver))
if getattr(receiver, 'im_self', None) is not None:
text = "%s.%s" % (getattr(receiver.im_self, '__class__', type).__name__, receiver_name)
elif getattr(receiver, 'im_class', None) is not None:
if getattr(receiver, '__self__', None) is not None:
text = "%s.%s" % (getattr(receiver.__self__, '__class__', type).__name__, receiver_name)
elif getattr(receiver, 'im_class', None) is not None: # Python 2 only
text = "%s.%s" % (receiver.im_class.__name__, receiver_name)
else:
text = "%s" % receiver_name
Expand Down
Loading