[PATCH 1 of 3] py3: re-implement the BaseHTTPServer.test() function

Yuya Nishihara yuya at tcha.org
Thu Jul 14 10:39:53 EDT 2016


On Thu, 14 Jul 2016 14:35:07 +0530, Pulkit Goyal wrote:
> # HG changeset patch
> # User Pulkit Goyal <7895pulkit at gmail.com>
> # Date 1468430122 -19800
> #      Wed Jul 13 22:45:22 2016 +0530
> # Node ID c8da57d0799eadf41bd838c5c2e334bde0c830ae
> # Parent  e5b4d79a9140c3d90e9b6aa22070351b73ef2d4c
> py3: re-implement the BaseHTTPServer.test() function
> 
> The function is changed in python 3, it does not use sys.argv now,
> rather it parses the command line now. So the latest version of function is
> re-implemented. One can look at https://hg.python.org/cpython/file/3.5/Lib/http/server.py#l1184
>  and https://hg.python.org/cpython/file/2.7/Lib/BaseHTTPServer.py#l590 to see the change.
> 
> diff -r e5b4d79a9140 -r c8da57d0799e tests/tinyproxy.py
> --- a/tests/tinyproxy.py	Sat May 21 15:23:21 2016 +0900
> +++ b/tests/tinyproxy.py	Wed Jul 13 22:45:22 2016 +0530
> @@ -15,6 +15,7 @@
>  __version__ = "0.2.1"
>  
>  import BaseHTTPServer
> +import argparse
>  import os
>  import select
>  import socket
> @@ -143,6 +144,19 @@
>          a.write(str(os.getpid()) + "\n")
>          a.close()
>  
> +def runserver(port=8000, bind=""):
> +    server_address = (bind, port)
> +    ProxyHandler.protocol_version = "HTTP/1.0"
> +    httpd = ThreadingHTTPServer(server_address, ProxyHandler)
> +    sa = httpd.socket.getsockname()
> +    print("Serving HTTP on", sa[0], "port", sa[1], "...")
> +    try:
> +        httpd.serve_forever()
> +    except KeyboardInterrupt:
> +        print("\nKeyboard interrupt received, exiting.")
> +        httpd.server_close()
> +        sys.exit(0)
> +
>  if __name__ == '__main__':
>      argv = sys.argv
>      if argv[1:] and argv[1] in ('-h', '--help'):
> @@ -158,4 +172,14 @@
>              del argv[2:]
>          else:
>              print("Any clients will be served...")
> -        BaseHTTPServer.test(ProxyHandler, ThreadingHTTPServer)
> +
> +        parser = argparse.ArgumentParser()
> +        parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
> +                        help='Specify alternate bind address '
> +                             '[default: all interfaces]')
> +        parser.add_argument('port', action='store',
> +                        default=8000, type=int,
> +                        nargs='?',
> +                        help='Specify alternate port [default: 8000]')
> +        args = parser.parse_args()
> +        runserver(port=args.port, bind=args.bind)

argparse is Python 2.7 thing. Please use optparse instead.


More information about the Mercurial-devel mailing list