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