Created
March 18, 2021 16:06
-
-
Save aodin/d94fa1f7b2ea42bc745d3ea9bf14f6b6 to your computer and use it in GitHub Desktop.
Standalone version of the server started by `python3 -m http.server`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A standalone version of the server started by `python3 -m http.server`. | |
Copied from Python 3.9 source. | |
""" | |
import contextlib | |
from functools import partial | |
import http.server | |
import os | |
import socket | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--cgi', action='store_true', | |
help='Run as CGI Server') | |
parser.add_argument('--bind', '-b', metavar='ADDRESS', | |
help='Specify alternate bind address ' | |
'[default: all interfaces]') | |
parser.add_argument('--directory', '-d', default=os.getcwd(), | |
help='Specify alternative directory ' | |
'[default:current directory]') | |
parser.add_argument('port', action='store', | |
default=8000, type=int, | |
nargs='?', | |
help='Specify alternate port [default: 8000]') | |
args = parser.parse_args() | |
if args.cgi: | |
handler_class = http.server.CGIHTTPRequestHandler | |
else: | |
handler_class = partial(http.server.SimpleHTTPRequestHandler, | |
directory=args.directory) | |
# ensure dual-stack is not disabled; ref #38907 | |
class DualStackServer(http.server.ThreadingHTTPServer): | |
def server_bind(self): | |
# suppress exception when protocol is IPv4 | |
with contextlib.suppress(Exception): | |
self.socket.setsockopt( | |
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) | |
return super().server_bind() | |
http.server.test( | |
HandlerClass=handler_class, | |
ServerClass=DualStackServer, | |
port=args.port, | |
bind=args.bind, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment