我只是运行以下命令来生成自签名证书:
openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
Run Code Online (Sandbox Code Playgroud)
执行命令后,我回答了一些关于我的位置等的问题。生成证书时没有错误。然后我添加app.run(ssl_context=('cert.pem', 'key.pem'))
到我的 Flask 应用程序中。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
""" Home page of the website """
return render_template('index.html')
... Some other functions ...
if __name__ == "__main__":
app.run(ssl_context=('cert.pem', 'key.pem'))
Run Code Online (Sandbox Code Playgroud)
问题是没有任何东西通过 HTTPS 传送。当我运行应用程序时,我得到:
$ flask run
* Running on http://0.0.0.0:5000/
Run Code Online (Sandbox Code Playgroud)
我可以使用 HTTP 正常访问页面,但是当我尝试执行 HTTPS 时,我的浏览器出现以下错误:
An error occurred during a connection to XXXXXXX.XXX.edu:5000.
SSL received a record that exceeded the maximum permissible length.
Error code: SSL_ERROR_RX_RECORD_TOO_LONG
Run Code Online (Sandbox Code Playgroud)
我在我的服务器上收到以下错误:
code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x00\xbd\x01\x00\x00\xb9\x03\x03\xbc\x1c\xc6q#\xdcr')
Run Code Online (Sandbox Code Playgroud)
为什么我无法使用 HTTPS 查看内容?
免责声明:我知道如果有人想做生产级编码,他们应该使用 nginx 或 gunicorn 来提供 HTTPS 服务。我目前只是为了测试而尝试使用 Flask。
您的确切代码在 Python 2.7.12 和 Python 3.5.2 中对我来说都运行良好。
此外,从服务器错误我可以告诉你的服务器期望一个普通的 HTTP 请求,而不是一个 TLS 握手。
\x16\x03\x01..
是ClientHello数据包的开始,它说嘿服务器,让我们启动一个 TLS 通道,这里有一些加密位。
您的服务器似乎试图将其解释为 HTTP 请求,这就是您看到HTTP 400 Bad request
. 从您在评论中发布的 CLI 输出中可以看出这一点:
当应用程序实际启动时,它会显示
Running on http://0.0.0.0:5000/
.
请注意http
代替https
。
长话短说,你的 Python/Flask 安装有问题。尝试从头开始重新安装 Python。
我错过了你说你正在运行flask run
而不是运行的部分python app.py
。似乎只有前者会启动 TLS 侦听器。
要么flask run
根本无法执行 TLS,要么我们需要传入一个未记录的参数,这将是零意义的。
答案在这里 - /sf/answers/3392763181/