serve.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env python3
  2. '''
  3. Small wsgiref based web server. Takes a path to serve from and an
  4. optional port number (defaults to 8000), then tries to serve files.
  5. Mime types are guessed from the file names, 404 errors are raised
  6. if the file is not found. Used for the make serve target in Doc.
  7. '''
  8. import sys
  9. import os
  10. import mimetypes
  11. from wsgiref import simple_server, util
  12. def app(environ, respond):
  13. fn = os.path.join(path, environ['PATH_INFO'][1:])
  14. if '.' not in fn.split(os.path.sep)[-1]:
  15. fn = os.path.join(fn, 'index.html')
  16. type = mimetypes.guess_type(fn)[0]
  17. if os.path.exists(fn):
  18. respond('200 OK', [('Content-Type', type)])
  19. return util.FileWrapper(open(fn, "rb"))
  20. else:
  21. respond('404 Not Found', [('Content-Type', 'text/plain')])
  22. return [b'not found']
  23. if __name__ == '__main__':
  24. path = sys.argv[1]
  25. port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
  26. httpd = simple_server.make_server('', port, app)
  27. print("Serving {} on port {}, control-C to stop".format(path, port))
  28. try:
  29. httpd.serve_forever()
  30. except KeyboardInterrupt:
  31. print("\b\bShutting down.")