blob: dae21f2260ff13e9c63d46e2330f5d36111e97f5 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
R. David Murraye821cb62010-03-08 17:48:38 +00002'''
3Small wsgiref based web server. Takes a path to serve from and an
4optional port number (defaults to 8000), then tries to serve files.
Andrew Svetlov737fb892012-12-18 21:14:22 +02005Mime types are guessed from the file names, 404 errors are raised
R. David Murraye821cb62010-03-08 17:48:38 +00006if the file is not found. Used for the make serve target in Doc.
7'''
8import sys
9import os
10import mimetypes
11from wsgiref import simple_server, util
12
13def app(environ, respond):
14
15 fn = os.path.join(path, environ['PATH_INFO'][1:])
16 if '.' not in fn.split(os.path.sep)[-1]:
17 fn = os.path.join(fn, 'index.html')
18 type = mimetypes.guess_type(fn)[0]
19
20 if os.path.exists(fn):
21 respond('200 OK', [('Content-Type', type)])
Antoine Pitrouf767f082010-08-03 17:09:36 +000022 return util.FileWrapper(open(fn, "rb"))
R. David Murraye821cb62010-03-08 17:48:38 +000023 else:
24 respond('404 Not Found', [('Content-Type', 'text/plain')])
Serhiy Storchaka02d5db22014-01-11 11:52:20 +020025 return [b'not found']
R. David Murraye821cb62010-03-08 17:48:38 +000026
27if __name__ == '__main__':
28 path = sys.argv[1]
29 port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
30 httpd = simple_server.make_server('', port, app)
R. David Murray5ab2e742010-05-31 23:23:50 +000031 print("Serving {} on port {}, control-C to stop".format(path, port))
32 try:
33 httpd.serve_forever()
34 except KeyboardInterrupt:
35 print("\b\bShutting down.")