You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

64 lines
1.6 KiB

  1. import bobo, mimetypes, os, webob
  2. class Directory:
  3. def __init__(self, root, path=None):
  4. self.root = os.path.abspath(root) + os.path.sep
  5. self.path = path or root
  6. @bobo.query("")
  7. def base(self, bobo_request):
  8. return bobo.redirect(bobo_request.url + "/")
  9. @bobo.query("/")
  10. def index(self):
  11. links = []
  12. for name in os.listdir(self.path):
  13. if os.path.isdir(os.path.join(self.path, name)):
  14. name += "/"
  15. links.append('<a href="%s">%s</a>' % (name, name))
  16. return """<html>
  17. <head><title>%s</title></head>
  18. <body>
  19. %s
  20. </body>
  21. </html>
  22. """ % (
  23. self.path[len(self.root) :],
  24. "<br>\n ".join(links),
  25. )
  26. @bobo.subroute("/:name")
  27. def traverse(self, request, name):
  28. path = os.path.abspath(os.path.join(self.path, name))
  29. if not path.startswith(self.root):
  30. raise bobo.NotFound
  31. if os.path.isdir(path):
  32. return Directory(self.root, path)
  33. else:
  34. return File(path)
  35. bobo.scan_class(Directory)
  36. class File:
  37. def __init__(self, path):
  38. self.path = path
  39. @bobo.query("")
  40. def base(self, bobo_request):
  41. response = webob.Response()
  42. content_type = mimetypes.guess_type(self.path)[0]
  43. if content_type is not None:
  44. response.content_type = content_type
  45. try:
  46. response.body = open(self.path).read()
  47. except IOError:
  48. raise bobo.NotFound
  49. return response
  50. bobo.scan_class(File)