"""
Small wsgiref based web server. Takes a path to serve from and an
optional port number (defaults to 8000), then tries to serve files.
MIME types are guessed from the file names, 404 errors are raised
if the file is not found.
"""import mimetypes
import os
import sys
from wsgiref import simple_server, util
from urllib.parse import parse_qs
defapp(environ, respond):
get_query_ =environ['QUERY_STRING']
post_query_=environ["wsgi.input"].read(int(e)).decode("utf-8",'ignore')if(e:=environ.get("CONTENT_LENGTH"))elseNone
get_query =parse_qs(get_query_)
post_query=parse_qs(post_query_)print("REQUEST_METHOD: "+environ['REQUEST_METHOD'])print("GET : ",(get_query))print("POST: ",(post_query))if(environ["PATH_INFO"].startswith(r"/post")):
respond("200 OK",[("Content-Type","text/html; charset=utf-8")])
message=("Welcome, "+e[0]+" !")if(e:=post_query.get('username'))else"Welcome ! "
html ='''<!DOCTYPE HTML>
<html>
<head>
<title>Post page</title>
</head>
<body>
<h1> %s </h1>
Post Data:<br> %s <br />
Path:<br> %s <br />
</body>
</html>'''%( message,str(post_query), environ["PATH_INFO"])return[html.encode("utf-8")]else:# Get the file name and MIME type
fn = os.path.join(path,"res", environ["PATH_INFO"][1:])if"."notin fn.split(os.path.sep)[-1]:
fn = os.path.join(fn,"index.html")
mime_type = mimetypes.guess_type(fn)[0]# Return 200 OK if file exists, otherwise 404 Not Foundif os.path.exists(fn):
respond("200 OK",[("Content-Type", mime_type)])return util.FileWrapper(open(fn,"rb"))else:
respond("404 Not Found",[("Content-Type","text/plain")])return[b"not found"]if __name__ =="__main__":# Get the path and port from command-line arguments
path = sys.argv[1]iflen(sys.argv)>1else os.getcwd()
port =int(sys.argv[2])iflen(sys.argv)>2else8000# Make and start the server until control-c
httpd = simple_server.make_server("", port, app)print(f"Serving {path} on port {port}, control-C to stop")try:
httpd.serve_forever()except KeyboardInterrupt:print("Shutting down.")
httpd.server_close()