@@ -781,3 +781,35 @@ This is a working "Hello World" WSGI application::
|
781 | 781 | |
782 | 782 | # Serve until process is killed |
783 | 783 | httpd.serve_forever() |
| 784 | + |
| 785 | + |
| 786 | +Example of a small wsgiref-based web server:: |
| 787 | + |
| 788 | + # Takes a path to serve from and an optional port number (defaults to 8000), |
| 789 | + # then tries to serve files. Mime types are guessed from the file names, 404 |
| 790 | + # errors are raised if the file is not found. |
| 791 | + import sys |
| 792 | + import os |
| 793 | + import mimetypes |
| 794 | + from wsgiref import simple_server, util |
| 795 | + |
| 796 | + def app(environ, respond): |
| 797 | + fn = os.path.join(path, environ['PATH_INFO'][1:]) |
| 798 | + if '.' not in fn.split(os.path.sep)[-1]: |
| 799 | + fn = os.path.join(fn, 'index.html') |
| 800 | + type = mimetypes.guess_type(fn)[0] |
| 801 | + |
| 802 | + if os.path.exists(fn): |
| 803 | + respond('200 OK', [('Content-Type', type)]) |
| 804 | + return util.FileWrapper(open(fn, "rb")) |
| 805 | + else: |
| 806 | + respond('404 Not Found', [('Content-Type', 'text/plain')]) |
| 807 | + return [b'not found'] |
| 808 | + |
| 809 | + path = sys.argv[1] |
| 810 | + port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 |
| 811 | + with simple_server.make_server('', port, app) as httpd: |
| 812 | + print("Serving {} on port {}, control-C to stop".format(path, port)) |
| 813 | + |
| 814 | + # Serve until process is killed |
| 815 | + httpd.serve_forever() |