jqueryFileTree connector script for python cgi

If you use jquery and haven’t messed with the jqueryFileTree plugin, I’d highly recommend you do so. It’s pretty neat, and there are connector scripts already written in various languages for use with this plugin. However, there wasn’t one for python cgi (there was one for django however). So, I wrote my own! Try it out:

# jqueryFileTree connector script for python cgi 
# Version: 1.0 / 10 August 2010
# Author: Charles Hamilton / musashi@nefaria.com
# Released under the GNU GPLv3
# Modifications and improvements are welcome

import os, cgi, cgitb, urllib, re
form = cgi.FieldStorage()

print 'Content-Type: text/html\n\n'
print '<ul class="jqueryFileTree" style="display: none;">'

path = urllib.unquote(form['dir'].value)

dirs = []
files = []

filelist = sorted(os.listdir(path))

for object in filelist:
    if os.path.isfile(path + '/' + object):
       ext = os.path.splitext(object)
        files.append('<li class="file ext_' + re.sub('\.', '', ext[1]) + '"><a href="#" rel="'+ path + object + '">'+ object + '</a></li>')
    elif os.path.isdir(path + '/' + object):
        dirs.append('<li class="directory collapsed"><a href="#" rel="'+ path + object +'/">' + object + '</a></li>')

for d in dirs:
    print d

for f in files:
    print f
print '</ul>'

2 thoughts on “jqueryFileTree connector script for python cgi

  1. musashi says:

    The reason I don’t do it that way is due to performance. This would work fine on directory trees with few nodes, but imagine how long it would take to build the directory list if you decided to use this to display “/” (not that you’d ever, ever do this… ever.)

  2. mart says:

    Hi, was looking for something about jquery (filetree stuff, etc). Anyways, came across this page. I thought, “hey! this is very cool! and a great idea, get python to script the js script!” – much easier this way :) Anyways, just made a few little tweaks to make it recursive. Now I’ll get python to do the rest of the script this way!

    Thanks for the tip!

    Mart :)

    import os,re
    from collections import deque
    import string

    path = ‘/Users/mart/test’
    filesDirs = deque()
    def main():

    def doIt(filelist):
    for object in filelist:
    if os.path.isfile(object):
    elif os.path.isdir(object):

    def getFileList():
    filelist = deque()
    for root,dirs,files in os.walk(path):
    for f in files:
    mPath = string.replace(“{0}/{1}”.format(root,
    return filelist

    def doFile(mPath):
    tail,head = os.path.split(mPath)
    ext = os.path.splitext(head)
    def doDir(d):

    def printAll():
    s = ‘Content-Type: text/html\n\n’
    for item in filesDirs:
    s += “\n{0}”.format(item)
    s += ‘\n’
    print s

    if ‘__main__’:

Comments are closed.