【发布时间】: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
是否可以使用 SSL 证书创建临时 Python3 HTTP 服务器?例如:
$ python3 -m http.server 443 --certificate /path/to/cert
【问题讨论】:
标签: python python-3.x http ssl server
不是从命令行,但编写一个简单的脚本来执行此操作非常简单。
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()
如果你不局限于标准库并且可以安装 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.。
实际上没有,但是有一个实现使用与 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
【讨论】: