Serotonin Storm

source>source>views.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import os
from pygments.lexers import get_lexer_for_filename, JavascriptLexer, TextLexer, HtmlDjangoLexer
from pygments.formatters import HtmlFormatter
from pygments import highlight
from pygments.styles import get_style_by_name
from django.shortcuts import render_to_response
from django.http import HttpResponseBadRequest, Http404
from django.conf import settings
from django.template.context import RequestContext


def pygdoc(request, path):
    if path.endswith('/'): path = path[:-1]
    abspath = os.path.abspath(os.path.join(settings.PROJECT_ROOT, path))
    if abspath.endswith('.pyc'):
        abspath = abspath[:-4]
    if os.path.isfile(abspath):
        formatter = HtmlFormatter(linenos=True,cssclass='codehilite',style=get_style_by_name('native'))
        
        if abspath.endswith('.json'):
            lexer = JavascriptLexer()
        elif abspath.endswith('.html'):
            lexer = HtmlDjangoLexer()
        else:
            try:
                lexer = get_lexer_for_filename(abspath)
            except:
                lexer = TextLexer()
        
        if abspath.endswith('.db') or abspath.endswith('.jpg') or abspath.endswith('.png') or abspath.endswith('.gif') or abspath.endswith('local_settings.py') :
            source = 'Un-highlightable file type'
        else:
            source = open(abspath).read()
        
        return render_to_response('source.html', {
            'source': highlight(source, lexer, formatter)},
                                  context_instance = RequestContext(request))
    elif os.path.isdir(abspath) and not abspath.endswith('.svn'):
        contents = [os.path.join(abspath, f) for f in os.listdir(abspath) if not f.startswith('.') and not f.endswith('.pyc')]
        return render_to_response('directory.html', {
            'files': sorted([f[len(abspath)+1:] for f in contents if os.path.isfile(f)]),
            'folders': sorted([f[len(abspath)+1:] for f in contents if os.path.isdir(f)])
            },  context_instance = RequestContext(request))
    else:
        raise Http404