I came up with a small patch for 3.1.0rc1 to implement optional
directory browsing for static directories.
Setting tools.staticdir.generate_indexes=True turns it on.. Setting
the config to a callable lets you generate generate indexes yourself.
No doubt this is imperfect in many ways, but I figured it might be a
useful starting point.
*** static.py 2008-05-17 13:34:25.000000000 -0700
--- static-with-indexes.py 2008-05-30 18:03:11.000000000 -0700
***************
*** 148,154 ****
# request. We might find a dynamic handler instead.
return False
! def staticdir(section, dir, root="", match="", content_types=None,
index=""):
"""Serve a static resource from the given (root +) dir."""
if match and not re.search(match, cherrypy.request.path_info):
return False
--- 148,203 ----
# request. We might find a dynamic handler instead.
return False
! _INDEX_TEMPLATE = '''
! <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
! "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
! <html>
! <head>
! <meta http-equiv="Content-Type" content="text/html;
charset=utf-8"></meta>
! <title>%(title)s</title>
! <style type="text/css">
! #powered_by {
! margin-top: 20px;
! border-top: 2px solid black;
! font-style: italic;
! }
! </style>
! </head>
! <body>
! <h2>%(title)s</h2>
! <ul id="filelist">
! %(filelist)s
! </ul>
! <div id="powered_by">
! <span>Powered by <a href="
http://www.cherrypy.org">CherryPy %
(version)s</a></span>
! </div>
! </body>
! </html>
! '''
!
! def render_index(path, branch):
! import cgi
! path = unicode(path)
! files = os.listdir(path)
! files.sort()
! filelist = []
! if branch:
! filelist.append('<li><a href="../">Parent Directory</a></
li>')
! for fn in files:
! fnquote = cgi.escape(fn.encode('utf-8'))
! if os.path.isdir(os.path.join(path, fn)):
! filelist.append('<li><a href="%s/">%s</a></li>' %
(fnquote, fnquote))
! else:
! filelist.append('<li><a href="%s">%s</a></li>' %
(fnquote, fnquote))
! cherrypy.response.body = _INDEX_TEMPLATE % {
! 'title' : "Index of /%s" % cgi.escape(branch.strip('/')),
! 'filelist' : "\n".join(filelist),
! 'version' : cherrypy.__version__
! }
! return True
!
!
! def staticdir(section, dir, root="", match="", content_types=None,
index="", generate_indexes=False):
"""Serve a static resource from the given (root +) dir."""
if match and not re.search(match, cherrypy.request.path_info):
return False
***************
*** 187,192 ****
--- 236,246 ----
handled = _attempt(os.path.join(filename, index),
content_types)
if handled:
cherrypy.request.is_index = filename[-1] in (r"\/")
+ if not handled and generate_indexes:
+ if callable(generate_indexes):
+ handled = generate_indexes(filename, branch)
+ else:
+ handled = render_index(filename, branch)
return handled
def staticfile(filename, root=None, match="", content_types=None):