【问题标题】:Python -m http.server 443 -- with SSL?Python -m http.server 443 - 使用 SSL?
【发布时间】:2019-06-08 03:43:41
【问题描述】:

是否可以使用 SSL 证书创建临时 Python3 HTTP 服务器?例如:

$ python3 -m http.server 443 --certificate /path/to/cert

【问题讨论】:

    标签: python python-3.x http ssl server


    【解决方案1】:

    不是从命令行,但编写一个简单的脚本来执行此操作非常简单。

    from http.server import HTTPServer, BaseHTTPRequestHandler 
    import ssl
    httpd = HTTPServer(('localhost', 4443), BaseHTTPRequestHandler)
    httpd.socket = ssl.wrap_socket(
        httpd.socket,
        keyfile="path/to/key.pem",
        certfile='path/to/cert.pem',
        server_side=True)
    httpd.serve_forever()
    

    Credit

    如果你不局限于标准库并且可以安装 pip 包,还有许多其他选项,例如你可以安装 uwsgi,它接受命令行选项。

    【讨论】:

    • 谢谢!尽管“这行得通”,它还需要继承 BaseHTTPRequestHandler 并实现您自己的 do_GET(如果需要,还需要实现 do_POST)。没有它(就像答案一样),这导致我在网络浏览器中出现Error code: 501 , Message: "Unsupported method ('GET')" , Error code explanation: HTTPStatus.NOT_IMPLEMENTED - Server does not support this operation.
    【解决方案2】:

    实际上没有,但是有一个实现使用与 ssl 相同的包。 你应该try it

    该脚本是使用 Python 2 编写的,但使用 Python 3 很容易再次实现,因为它只有 5 行。

    http.server 是 Python 3 中的,相当于 Python 2 中的 SimpleHTTPServer。

    import BaseHTTPServer, SimpleHTTPServer
    import ssl
    
    httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
    httpd.serve_forever()
    

    脚本归功于dergachev

    【讨论】:

    • ModuleNotFoundError: 没有名为“BaseHTTPServer”的模块
    猜你喜欢
    • 2014-12-12
    • 2017-05-14
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2017-05-17
    相关资源
    最近更新 更多