Python -m http.server 443 - 使用 SSL?

vsk*_*vds 12 python ssl http python-3.x server

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

$ python3 -m http.server 443 --certificate /path/to/cert
Run Code Online (Sandbox Code Playgroud)

Lie*_*yan 10

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

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()
Run Code Online (Sandbox Code Playgroud)

信用

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

  • 如果您只需要提供类似于“python3 -m http.server”的文件,您也可以使用“SimpleHTTPServer.SimpleHTTPRequestHandler”。 (3认同)
  • 谢谢!尽管“这有效”,它还需要子类化 ```BaseHTTPRequestHandler``` 并实现您自己的 ```do_GET``` (如果需要,还需要 ```do_POST``` )。如果没有它(就像答案中一样),这会导致``错误代码:501,消息:“不支持的方法('GET')”,错误代码解释:HTTPStatus.NOT_IMPLMENTED - 服务器不支持此操作。`` ` 在我的网络浏览器中。 (2认同)
  • 用 `SimpleHTTPRequestHandler` 替换 `BaseHTTPRequestHandler` 是有效的,它的注销与 `python3 -m http.server` 相同 (2认同)

Hor*_*rus 2

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

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

Python 3 中的 http.server 相当于 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()
Run Code Online (Sandbox Code Playgroud)

剧本归功于德加乔夫

  • ModuleNotFoundError:没有名为“BaseHTTPServer”的模块 (3认同)