Python 3 简单的 HTTPS 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19705785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:24:22  来源:igfitidea点击:

Python 3 Simple HTTPS server

pythonhttps

提问by MANICX100

I know you can create a simple HTTP web server in Python 3 using

我知道您可以使用 Python 3 创建一个简单的 HTTP Web 服务器

python -m http.server

However is there a simple way to secure the connection to the WebServer, do i need to generate certificates? How would I do this?

但是,有没有一种简单的方法来保护与 WebServer 的连接,我是否需要生成证书?我该怎么做?

回答by Michael Foukarakis

First, you will need a certificate - assume we have it in a file localhost.pemwhich contains boththe private and public keys, then:

首先,你需要一个证书-假设我们有它在一个文件中localhost.pem包含两个私人和公共密钥,则:

import http.server, ssl

server_address = ('localhost', 4443)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
                               server_side=True,
                               certfile='localhost.pem',
                               ssl_version=ssl.PROTOCOL_TLSv1)
httpd.serve_forever()

Make sure you specify the right parameters for wrap_socket!

确保为wrap_socket!指定正确的参数!