Skip to content

Commit 2b7f93b

Browse files
authored
bpo-36345: Update wsgiref example (GH-12562)
Use literalinclude markup to include Tools/scripts/serve.py code. Tools/scripts/serve.py first argument on the command line is now optional.
1 parent 6fa84bd commit 2b7f93b

File tree

3 files changed

+10
-32
lines changed

3 files changed

+10
-32
lines changed

Doc/library/wsgiref.rst

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -783,33 +783,7 @@ This is a working "Hello World" WSGI application::
783783
httpd.serve_forever()
784784

785785

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()
786+
Example of a WSGI application serving the current directory, accept optional
787+
directory and port number (default: 8000) on the command line:
788+
789+
.. literalinclude:: ../../Tools/scripts/serve.py
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Avoid the duplication of code from ``Tools/scripts/serve.py`` in using the
2+
:rst:dir:`literalinclude` directive for the basic wsgiref-based web server in the
3+
documentation of :mod:`wsgiref`. Contributed by Stéphane Wirtel.

Tools/scripts/serve.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,12 @@ def app(environ, respond):
2525
return [b'not found']
2626

2727
if __name__ == '__main__':
28-
path = sys.argv[1]
28+
path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
2929
port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
3030
httpd = simple_server.make_server('', port, app)
3131
print("Serving {} on port {}, control-C to stop".format(path, port))
3232
try:
3333
httpd.serve_forever()
3434
except KeyboardInterrupt:
35-
print("\b\bShutting down.")
35+
print("Shutting down.")
36+
httpd.server_close()

0 commit comments

Comments
 (0)