Skip to content

Commit 360e1e4

Browse files
matrixisebrettcannon
authored andcommitted
bpo-36345: Add a new example in the documentation of wsgiref (#12511)
1 parent 1075d16 commit 360e1e4

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Doc/library/wsgiref.rst

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,3 +781,35 @@ This is a working "Hello World" WSGI application::
781781

782782
# Serve until process is killed
783783
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()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Using the code of the ``Tools/scripts/serve.py`` script as an example in the
2+
:mod:`wsgiref` documentation. Contributed by Stéphane Wirtel.

0 commit comments

Comments
 (0)