Django

Code

root/django/branches/newforms-admin/django/views/debug.py

Revision 7937, 29.2 kB (checked in by brosner, 5 months ago)

newforms-admin: Merged from trunk up to [7928].

  • Property svn:eol-style set to native
Line 
1 import os
2 import re
3 import sys
4 import datetime
5
6 from django.conf import settings
7 from django.template import Template, Context, TemplateDoesNotExist
8 from django.utils.html import escape
9 from django.http import HttpResponse, HttpResponseServerError, HttpResponseNotFound
10 from django.utils.encoding import smart_unicode
11
12 HIDDEN_SETTINGS = re.compile('SECRET|PASSWORD|PROFANITIES_LIST')
13
14 def linebreak_iter(template_source):
15     yield 0
16     p = template_source.find('\n')
17     while p >= 0:
18         yield p+1
19         p = template_source.find('\n', p+1)
20     yield len(template_source) + 1
21
22 def get_safe_settings():
23     "Returns a dictionary of the settings module, with sensitive settings blurred out."
24     settings_dict = {}
25     for k in dir(settings):
26         if k.isupper():
27             if HIDDEN_SETTINGS.search(k):
28                 settings_dict[k] = '********************'
29             else:
30                 settings_dict[k] = getattr(settings, k)
31     return settings_dict
32
33 def technical_500_response(request, exc_type, exc_value, tb):
34     """
35     Create a technical server error response. The last three arguments are
36     the values returned from sys.exc_info() and friends.
37     """
38     reporter = ExceptionReporter(request, exc_type, exc_value, tb)
39     html = reporter.get_traceback_html()
40     return HttpResponseServerError(html, mimetype='text/html')
41
42 class ExceptionReporter:
43     """
44     A class to organize and coordinate reporting on exceptions.
45     """
46     def __init__(self, request, exc_type, exc_value, tb):
47         self.request = request
48         self.exc_type = exc_type
49         self.exc_value = exc_value
50         self.tb = tb
51
52         self.template_info = None
53         self.template_does_not_exist = False
54         self.loader_debug_info = None
55
56         # Handle deprecated string exceptions
57         if isinstance(self.exc_type, basestring):
58             self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type)
59             self.exc_type = type(self.exc_value)
60
61     def get_traceback_html(self):
62         "Return HTML code for traceback."
63
64         if issubclass(self.exc_type, TemplateDoesNotExist):
65             from django.template.loader import template_source_loaders
66             self.template_does_not_exist = True
67             self.loader_debug_info = []
68             for loader in template_source_loaders:
69                 try:
70                     source_list_func = getattr(__import__(loader.__module__, {}, {}, ['get_template_sources']), 'get_template_sources')
71                     # NOTE: This assumes exc_value is the name of the template that
72                     # the loader attempted to load.
73                     template_list = [{'name': t, 'exists': os.path.exists(t)} \
74                         for t in source_list_func(str(self.exc_value))]
75                 except (ImportError, AttributeError):
76                     template_list = []
77                 self.loader_debug_info.append({
78                     'loader': loader.__module__ + '.' + loader.__name__,
79                     'templates': template_list,
80                 })
81         if settings.TEMPLATE_DEBUG and hasattr(self.exc_value, 'source'):
82             self.get_template_exception_info()
83
84         frames = self.get_traceback_frames()
85
86         unicode_hint = ''
87         if issubclass(self.exc_type, UnicodeError):
88             start = getattr(self.exc_value, 'start', None)
89             end = getattr(self.exc_value, 'end', None)
90             if start is not None and end is not None:
91                 unicode_str = self.exc_value.args[1]
92                 unicode_hint = smart_unicode(unicode_str[max(start-5, 0):min(end+5, len(unicode_str))], 'ascii', errors='replace')
93         from django import get_version
94         t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
95         c = Context({
96             'exception_type': self.exc_type.__name__,
97             'exception_value': smart_unicode(self.exc_value, errors='replace'),
98             'unicode_hint': unicode_hint,
99             'frames': frames,
100             'lastframe': frames[-1],
101             'request': self.request,
102             'request_protocol': self.request.is_secure() and "https" or "http",
103             'settings': get_safe_settings(),
104             'sys_executable': sys.executable,
105             'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
106             'server_time': datetime.datetime.now(),
107             'django_version_info': get_version(),
108             'sys_path' : sys.path,
109             'template_info': self.template_info,
110             'template_does_not_exist': self.template_does_not_exist,
111             'loader_debug_info': self.loader_debug_info,
112         })
113         return t.render(c)
114
115     def get_template_exception_info(self):
116         origin, (start, end) = self.exc_value.source
117         template_source = origin.reload()
118         context_lines = 10
119         line = 0
120         upto = 0
121         source_lines = []
122         before = during = after = ""
123         for num, next in enumerate(linebreak_iter(template_source)):
124             if start >= upto and end <= next:
125                 line = num
126                 before = escape(template_source[upto:start])
127                 during = escape(template_source[start:end])
128                 after = escape(template_source[end:next])
129             source_lines.append( (num, escape(template_source[upto:next])) )
130             upto = next
131         total = len(source_lines)
132
133         top = max(1, line - context_lines)
134         bottom = min(total, line + 1 + context_lines)
135
136         self.template_info = {
137             'message': self.exc_value.args[0],
138             'source_lines': source_lines[top:bottom],
139             'before': before,
140             'during': during,
141             'after': after,
142             'top': top,
143             'bottom': bottom,
144             'total': total,
145             'line': line,
146             'name': origin.name,
147         }
148         if hasattr(self.exc_value, 'exc_info') and self.exc_value.exc_info:
149             exc_type, exc_value, tb = self.exc_value.exc_info
150
151     def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
152         """
153         Returns context_lines before and after lineno from file.
154         Returns (pre_context_lineno, pre_context, context_line, post_context).
155         """
156         source = None
157         if loader is not None and hasattr(loader, "get_source"):
158             source = loader.get_source(module_name)
159             if source is not None:
160                 source = source.splitlines()
161         if source is None:
162             try:
163                 f = open(filename)
164                 try:
165                     source = f.readlines()
166                 finally:
167                     f.close()
168             except (OSError, IOError):
169                 pass
170         if source is None:
171             return None, [], None, []
172
173         encoding = 'ascii'
174         for line in source[:2]:
175             # File coding may be specified. Match pattern from PEP-263
176             # (http://www.python.org/dev/peps/pep-0263/)
177             match = re.search(r'coding[:=]\s*([-\w.]+)', line)
178             if match:
179                 encoding = match.group(1)
180                 break
181         source = [unicode(sline, encoding, 'replace') for sline in source]
182
183         lower_bound = max(0, lineno - context_lines)
184         upper_bound = lineno + context_lines
185
186         pre_context = [line.strip('\n') for line in source[lower_bound:lineno]]
187         context_line = source[lineno].strip('\n')
188         post_context = [line.strip('\n') for line in source[lineno+1:upper_bound]]
189
190         return lower_bound, pre_context, context_line, post_context
191
192     def get_traceback_frames(self):
193         frames = []
194         tb = self.tb
195         while tb is not None:
196             # support for __traceback_hide__ which is used by a few libraries
197             # to hide internal frames.
198             if tb.tb_frame.f_locals.get('__traceback_hide__'):
199                 tb = tb.tb_next
200                 continue
201             filename = tb.tb_frame.f_code.co_filename
202             function = tb.tb_frame.f_code.co_name
203             lineno = tb.tb_lineno - 1
204             loader = tb.tb_frame.f_globals.get('__loader__')
205             module_name = tb.tb_frame.f_globals.get('__name__')
206             pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file(filename, lineno, 7, loader, module_name)
207             if pre_context_lineno is not None:
208                 frames.append({
209                     'tb': tb,
210                     'filename': filename,
211                     'function': function,
212                     'lineno': lineno + 1,
213                     'vars': tb.tb_frame.f_locals.items(),
214                     'id': id(tb),
215                     'pre_context': pre_context,
216                     'context_line': context_line,
217                     'post_context': post_context,
218                     'pre_context_lineno': pre_context_lineno + 1,
219                 })
220             tb = tb.tb_next
221
222         if not frames:
223             frames = [{
224                 'filename': '&lt;unknown&gt;',
225                 'function': '?',
226                 'lineno': '?',
227                 'context_line': '???',
228             }]
229
230         return frames
231
232     def format_exception(self):
233         """
234         Return the same data as from traceback.format_exception.
235         """
236         import traceback
237         frames = self.get_traceback_frames()
238         tb = [ (f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames ]
239         list = ['Traceback (most recent call last):\n']
240         list += traceback.format_list(tb)
241         list += traceback.format_exception_only(self.exc_type, self.exc_value)
242         return list
243
244
245 def technical_404_response(request, exception):
246     "Create a technical 404 error response. The exception should be the Http404."
247     try:
248         tried = exception.args[0]['tried']
249     except (IndexError, TypeError):
250         tried = []
251     else:
252         if not tried:
253             # tried exists but is an empty list. The URLconf must've been empty.
254             return empty_urlconf(request)
255
256     t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
257     c = Context({
258         'root_urlconf': settings.ROOT_URLCONF,
259         'request_path': request.path[1:], # Trim leading slash
260         'urlpatterns': tried,
261         'reason': str(exception),
262         'request': request,
263         'request_protocol': request.is_secure() and "https" or "http",
264         'settings': get_safe_settings(),
265     })
266     return HttpResponseNotFound(t.render(c), mimetype='text/html')
267
268 def empty_urlconf(request):
269     "Create an empty URLconf 404 error response."
270     t = Template(EMPTY_URLCONF_TEMPLATE, name='Empty URLConf template')
271     c = Context({
272         'project_name': settings.SETTINGS_MODULE.split('.')[0]
273     })
274     return HttpResponse(t.render(c), mimetype='text/html')
275
276 #
277 # Templates are embedded in the file so that we know the error handler will
278 # always work even if the template loader is broken.
279 #
280
281 TECHNICAL_500_TEMPLATE = """
282 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
283 <html lang="en">
284 <head>
285   <meta http-equiv="content-type" content="text/html; charset=utf-8">
286   <meta name="robots" content="NONE,NOARCHIVE">
287   <title>{{ exception_type }} at {{ request.path|escape }}</title>
288   <style type="text/css">
289     html * { padding:0; margin:0; }
290     body * { padding:10px 20px; }
291     body * * { padding:0; }
292     body { font:small sans-serif; }
293     body>div { border-bottom:1px solid #ddd; }
294     h1 { font-weight:normal; }
295     h2 { margin-bottom:.8em; }
296     h2 span { font-size:80%; color:#666; font-weight:normal; }
297     h3 { margin:1em 0 .5em 0; }
298     h4 { margin:0 0 .5em 0; font-weight: normal; }
299     table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
300     tbody td, tbody th { vertical-align:top; padding:2px 3px; }
301     thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; }
302     tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
303     table.vars { margin:5px 0 2px 40px; }
304     table.vars td, table.req td { font-family:monospace; }
305     table td.code { width:100%; }
306     table td.code div { overflow:hidden; }
307     table.source th { color:#666; }
308     table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
309     ul.traceback { list-style-type:none; }
310     ul.traceback li.frame { margin-bottom:1em; }
311     div.context { margin: 10px 0; }
312     div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; }
313     div.context ol li { font-family:monospace; white-space:pre; color:#666; cursor:pointer; }
314     div.context ol.context-line li { color:black; background-color:#ccc; }
315     div.context ol.context-line li span { float: right; }
316     div.commands { margin-left: 40px; }
317     div.commands a { color:black; text-decoration:none; }
318     #summary { background: #ffc; }
319     #summary h2 { font-weight: normal; color: #666; }
320     #explanation { background:#eee; }
321     #template, #template-not-exist { background:#f6f6f6; }
322     #template-not-exist ul { margin: 0 0 0 20px; }
323     #unicode-hint { background:#eee; }
324     #traceback { background:#eee; }
325     #requestinfo { background:#f6f6f6; padding-left:120px; }
326     #summary table { border:none; background:transparent; }
327     #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
328     #requestinfo h3 { margin-bottom:-1em; }
329     .error { background: #ffc; }
330     .specific { color:#cc3300; font-weight:bold; }
331     h2 span.commands { font-size:.7em;}
332     span.commands a:link {color:#5E5694;}
333   </style>
334   <script type="text/javascript">
335   //<!--
336     function getElementsByClassName(oElm, strTagName, strClassName){
337         // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com
338         var arrElements = (strTagName == "*" && document.all)? document.all :
339         oElm.getElementsByTagName(strTagName);
340         var arrReturnElements = new Array();
341         strClassName = strClassName.replace(/\-/g, "\\-");
342         var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
343         var oElement;
344         for(var i=0; i<arrElements.length; i++){
345             oElement = arrElements[i];
346             if(oRegExp.test(oElement.className)){
347                 arrReturnElements.push(oElement);
348             }
349         }
350         return (arrReturnElements)
351     }
352     function hideAll(elems) {
353       for (var e = 0; e < elems.length; e++) {
354         elems[e].style.display = 'none';
355       }
356     }
357     window.onload = function() {
358       hideAll(getElementsByClassName(document, 'table', 'vars'));
359       hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
360       hideAll(getElementsByClassName(document, 'ol', 'post-context'));
361       hideAll(getElementsByClassName(document, 'div', 'pastebin'));
362     }
363     function toggle() {
364       for (var i = 0; i < arguments.length; i++) {
365         var e = document.getElementById(arguments[i]);
366         if (e) {
367           e.style.display = e.style.display == 'none' ? 'block' : 'none';
368         }
369       }
370       return false;
371     }
372     function varToggle(link, id) {
373       toggle('v' + id);
374       var s = link.getElementsByTagName('span')[0];
375       var uarr = String.fromCharCode(0x25b6);
376       var darr = String.fromCharCode(0x25bc);
377       s.innerHTML = s.innerHTML == uarr ? darr : uarr;
378       return false;
379     }
380     function switchPastebinFriendly(link) {
381       s1 = "Switch to copy-and-paste view";
382       s2 = "Switch back to interactive view";
383       link.innerHTML = link.innerHTML == s1 ? s2 : s1;
384       toggle('browserTraceback', 'pastebinTraceback');
385       return false;
386     }
387     //-->
388   </script>
389 </head>
390 <body>
391 <div id="summary">
392   <h1>{{ exception_type }} at {{ request.path|escape }}</h1>
393   <h2>{{ exception_value|escape }}</h2>
394   <table class="meta">
395     <tr>
396       <th>Request Method:</th>
397       <td>{{ request.META.REQUEST_METHOD }}</td>
398     </tr>
399     <tr>
400       <th>Request URL:</th>
401       <td>{{ request_protocol }}://{{ request.META.HTTP_HOST }}{{ request.path|escape }}</td>
402     </tr>
403     <tr>
404       <th>Exception Type:</th>
405       <td>{{ exception_type }}</td>
406     </tr>
407     <tr>
408       <th>Exception Value:</th>
409       <td>{{ exception_value|escape }}</td>
410     </tr>
411     <tr>
412       <th>Exception Location:</th>
413       <td>{{ lastframe.filename|escape }} in {{ lastframe.function|escape }}, line {{ lastframe.lineno }}</td>
414     </tr>
415     <tr>
416       <th>Python Executable:</th>
417       <td>{{ sys_executable|escape }}</td>
418     </tr>
419     <tr>
420       <th>Python Version:</th>
421       <td>{{ sys_version_info }}</td>
422     </tr>
423     <tr>
424       <th>Python Path:</th>
425       <td>{{ sys_path }}</td>
426     </tr>
427     <tr>
428       <th>Server time:</th>
429       <td>{{server_time|date:"r"}}</td>
430     </tr>
431   </table>
432 </div>
433 {% if unicode_hint %}
434 <div id="unicode-hint">
435     <h2>Unicode error hint</h2>
436     <p>The string that could not be encoded/decoded was: <strong>{{ unicode_hint|escape }}</strong></p>
437 </div>
438 {% endif %}
439 {% if template_does_not_exist %}
440 <div id="template-not-exist">
441     <h2>Template-loader postmortem</h2>
442     {% if loader_debug_info %}
443         <p>Django tried loading these templates, in this order:</p>
444         <ul>
445         {% for loader in loader_debug_info %}
446             <li>Using loader <code>{{ loader.loader }}</code>:
447                 <ul>{% for t in loader.templates %}<li><code>{{ t.name }}</code> (File {% if t.exists %}exists{% else %}does not exist{% endif %})</li>{% endfor %}</ul>
448             </li>
449         {% endfor %}
450         </ul>
451     {% else %}
452         <p>Django couldn't find any templates because your <code>TEMPLATE_LOADERS</code> setting is empty!</p>
453     {% endif %}
454 </div>
455 {% endif %}
456 {% if template_info %}
457 <div id="template">
458    <h2>Template error</h2>
459    <p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p>
460    <h3>{{ template_info.message }}</h3>
461    <table class="source{% if template_info.top %} cut-top{% endif %}{% ifnotequal template_info.bottom template_info.total %} cut-bottom{% endifnotequal %}">
462    {% for source_line in template_info.source_lines %}
463    {% ifequal source_line.0 template_info.line %}
464        <tr class="error"><th>{{ source_line.0 }}</th>
465        <td>{{ template_info.before }}<span class="specific">{{ template_info.during }}</span>{{ template_info.after }}</td></tr>
466    {% else %}
467       <tr><th>{{ source_line.0 }}</th>
468       <td>{{ source_line.1 }}</td></tr>
469    {% endifequal %}
470    {% endfor %}
471    </table>
472 </div>
473 {% endif %}
474 <div id="traceback">
475   <h2>Traceback <span class="commands"><a href="#" onclick="return switchPastebinFriendly(this);">Switch to copy-and-paste view</a></span></h2>
476   {% autoescape off %}
477   <div id="browserTraceback">
478     <ul class="traceback">
479       {% for frame in frames %}
480         <li class="frame">
481           <code>{{ frame.filename|escape }}</code> in <code>{{ frame.function|escape }}</code>
482
483           {% if frame.context_line %}
484             <div class="context" id="c{{ frame.id }}">
485               {% if frame.pre_context %}
486                 <ol start="{{ frame.pre_context_lineno }}" class="pre-context" id="pre{{ frame.id }}">{% for line in frame.pre_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ line|escape }}</li>{% endfor %}</ol>
487               {% endif %}
488               <ol start="{{ frame.lineno }}" class="context-line"><li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ frame.context_line|escape }} <span>...</span></li></ol>
489               {% if frame.post_context %}
490                 <ol start='{{ frame.lineno|add:"1" }}' class="post-context" id="post{{ frame.id }}">{% for line in frame.post_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ line|escape }}</li>{% endfor %}</ol>
491               {% endif %}
492             </div>
493           {% endif %}
494
495           {% if frame.vars %}
496             <div class="commands">
497                 <a href="#" onclick="return varToggle(this, '{{ frame.id }}')"><span>&#x25b6;</span> Local vars</a>
498             </div>
499             <table class="vars" id="v{{ frame.id }}">
500               <thead>
501                 <tr>
502                   <th>Variable</th>
503                   <th>Value</th>
504                 </tr>
505               </thead>
506               <tbody>
507                 {% for var in frame.vars|dictsort:"0" %}
508                   <tr>
509                     <td>{{ var.0|escape }}</td>
510                     <td class="code"><div>{{ var.1|pprint|escape }}</div></td>
511                   </tr>
512                 {% endfor %}
513               </tbody>
514             </table>
515           {% endif %}
516         </li>
517       {% endfor %}
518     </ul>
519   </div>
520   {% endautoescape %}
521   <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
522   <div id="pastebinTraceback" class="pastebin">
523     <input type="hidden" name="language" value="PythonConsole">
524     <input type="hidden" name="title" value="{{ exception_type|escape }} at {{ request.path|escape }}">
525     <input type="hidden" name="source" value="Django Dpaste Agent">
526     <input type="hidden" name="poster" value="Django">
527     <textarea name="content" id="traceback_area" cols="140" rows="25">
528 Environment:
529
530 Request Method: {{ request.META.REQUEST_METHOD }}
531 Request URL: {{ request_protocol }}://{{ request.META.HTTP_HOST }}{{ request.path|escape }}
532 Django Version: {{ django_version_info }}
533 Python Version: {{ sys_version_info }}
534 Installed Applications:
535 {{ settings.INSTALLED_APPS|pprint }}
536 Installed Middleware:
537 {{ settings.MIDDLEWARE_CLASSES|pprint }}
538
539 {% if template_does_not_exist %}Template Loader Error:
540 {% if loader_debug_info %}Django tried loading these templates, in this order:
541 {% for loader in loader_debug_info %}Using loader {{ loader.loader }}:
542 {% for t in loader.templates %}{{ t.name }} (File {% if t.exists %}exists{% else %}does not exist{% endif %})
543 {% endfor %}{% endfor %}
544 {% else %}Django couldn't find any templates because your TEMPLATE_LOADERS setting is empty!
545 {% endif %}
546 {% endif %}{% if template_info %}
547 Template error:
548 In template {{ template_info.name }}, error at line {{ template_info.line }}
549    {{ template_info.message }}{% for source_line in template_info.source_lines %}{% ifequal source_line.0 template_info.line %}
550    {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}
551 {% else %}
552    {{ source_line.0 }} : {{ source_line.1 }}
553 {% endifequal %}{% endfor %}{% endif %}
554 Traceback:
555 {% for frame in frames %}File "{{ frame.filename|escape }}" in {{ frame.function|escape }}
556 {% if frame.context_line %}  {{ frame.lineno }}. {{ frame.context_line|escape }}{% endif %}
557 {% endfor %}
558 Exception Type: {{ exception_type|escape }} at {{ request.path|escape }}
559 Exception Value: {{ exception_value|escape }}
560 </textarea>
561   <br><br>
562   <input type="submit" value="Share this traceback on a public Web site">
563   </div>
564 </form>
565 </div>
566
567 <div id="requestinfo">
568   <h2>Request information</h2>
569
570   <h3 id="get-info">GET</h3>
571   {% if request.GET %}
572     <table class="req">
573       <thead>
574         <tr>
575           <th>Variable</th>
576           <th>Value</th>
577         </tr>
578       </thead>
579       <tbody>
580         {% for var in request.GET.items %}
581           <tr>
582             <td>{{ var.0 }}</td>
583             <td class="code"><div>{{ var.1|pprint }}</div></td>
584           </tr>
585         {% endfor %}
586       </tbody>
587     </table>
588   {% else %}
589     <p>No GET data</p>
590   {% endif %}
591
592   <h3 id="post-info">POST</h3>
593   {% if request.POST %}
594     <table class="req">
595       <thead>
596         <tr>