/lib/galaxy/web/framework/middleware/static.py

https://bitbucket.org/ialbert/galaxy-genetrack · Python · 50 lines · 45 code · 3 blank · 2 comment · 10 complexity · e0ebe35b26cbe2076ee8f1807a8e3ca3 MD5 · raw file

  1. import os
  2. import sys
  3. import imp
  4. import pkg_resources
  5. import mimetypes
  6. from paste import request
  7. from paste import fileapp
  8. from paste.util import import_string
  9. from paste.deploy import converters
  10. from paste import httpexceptions
  11. from paste.httpheaders import ETAG
  12. from paste.urlparser import StaticURLParser
  13. class CacheableStaticURLParser( StaticURLParser ):
  14. def __init__( self, directory, cache_seconds=None ):
  15. StaticURLParser.__init__( self, directory )
  16. self.cache_seconds = cache_seconds
  17. def __call__( self, environ, start_response ):
  18. path_info = environ.get('PATH_INFO', '')
  19. if not path_info:
  20. return self.add_slash(environ, start_response)
  21. if path_info == '/':
  22. # @@: This should obviously be configurable
  23. filename = 'index.html'
  24. else:
  25. filename = request.path_info_pop(environ)
  26. full = os.path.join(self.directory, filename)
  27. if not os.path.exists(full):
  28. return self.not_found(environ, start_response)
  29. if os.path.isdir(full):
  30. # @@: Cache?
  31. return self.__class__(full)(environ, start_response)
  32. if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':
  33. return self.error_extra_path(environ, start_response)
  34. if_none_match = environ.get('HTTP_IF_NONE_MATCH')
  35. if if_none_match:
  36. mytime = os.stat(full).st_mtime
  37. if str(mytime) == if_none_match:
  38. headers = []
  39. ETAG.update(headers, mytime)
  40. start_response('304 Not Modified',headers)
  41. return [''] # empty body
  42. app = fileapp.FileApp(full)
  43. if self.cache_seconds:
  44. app.cache_control( max_age = int( self.cache_seconds ) )
  45. return app(environ, start_response)
  46. def make_static( global_conf, document_root, cache_seconds=None ):
  47. return CacheableStaticURLParser( document_root, cache_seconds )