您可以将 HTTPS 功能添加到 python Flask Web 服务器吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29458548/
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 04:35:02  来源:igfitidea点击:

can you add HTTPS functionality to a python flask web server?

pythonresthttpsflask

提问by robm

I am trying to build a web interface to Mock up a restful interface on networking device this networking device uses Digest Authentication and HTTPS. I figured out how to integrate Digest Authentication into the web server but I cannot seem to find out how to get https using FLASK if you can show me how please comment on what i would need to do with the code below to make that happen.

我正在尝试构建一个 Web 界面,以在该网络设备使用摘要式身份验证和 HTTPS 的网络设备上模拟一个安静的界面。我想出了如何将摘要式身份验证集成到 Web 服务器中,但我似乎无法找到如何使用 FLASK 获取 https,如果你能告诉我如何请评论我需要用下面的代码做什么来实现这一点。

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def index():
    return 'Flask is running!'


@app.route('/data')
def names():
    data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
    return jsonify(data)


if __name__ == '__main__':
    app.run()

采纳答案by RobM

this also works in a pinch

这也适用于紧要关头

from flask import Flask, jsonify


from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')




app = Flask(__name__)


@app.route('/')
def index():
    return 'Flask is running!'


@app.route('/data')
def names():
    data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
    return jsonify(data)


#if __name__ == '__main__':
#    app.run()
if __name__ == '__main__':  
     app.run(host='127.0.0.1', debug=True, ssl_context=context)

回答by Martijn Pieters

Deploy Flask on a real web server, rather than with the built-in (development) server.

将 Flask 部署在真正的 Web 服务器上,而不是使用内置(开发)服务器。

See the Deployment Optionschapterof the Flask documentation. Servers like Nginx and Apache both can handle setting up HTTPS servers rather than HTTP servers for your site.

请参阅Flask 文档的部署选项章节。像 Nginx 和 Apache 这样的服务器都可以为您的站点设置 HTTPS 服务器而不是 HTTP 服务器。

The standalone WSGI servers listed would typically be deployed behind Nginx and Apache in a proxy-forwarding configuration, where the front-end server handles the SSL encryption for you still.

列出的独立 WSGI 服务器通常在代理转发配置中部署在 Nginx 和 Apache 后面,其中前端服务器仍然为您处理 SSL 加密。

回答by anand tripathi

Don't use openssl or pyopensslits now become obselete in python

不要使用openssl 或 pyopenssl它现在在 python 中已过时

Refer the Code below

参考下面的代码

from flask import Flask, jsonify
import os

ASSETS_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)


@app.route('/')
def index():
    return 'Flask is running!'


@app.route('/data')
def names():
    data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
    return jsonify(data)


if __name__ == '__main__':
    context = ('local.crt', 'local.key')#certificate and key files
    app.run(debug=True, ssl_context=context)

回答by Hemanth Kondapalli

If this webserver is only for testing and demoing purposes. You can use ngrok, a open source too that tunnels your http traffic.

如果此网络服务器仅用于测试和演示目的。您可以使用 ngrok,它也是一个开源的隧道,用于传输您的 http 流量。

Bascially ngrok creates a public URL (both http and https) and then tunnels the traffic to whatever port your Flask process is running on.

基本上,ngrok 创建一个公共 URL(http 和 https),然后将流量隧道传输到 Flask 进程正在运行的任何端口。

https://ngrok.com/product

https://ngrok.com/product

It only takes a couple minutes to set up. You first have to download the software. Then run the command
./ngrok http [port number your python process is running on]

只需几分钟即可完成设置。您首先必须下载该软件。然后运行命令
./ngrok http [你的 python 进程正在运行的端口号]

It will then open up a window in terminal giving you both an http and https url to access your web app.

然后它会在终端中打开一个窗口,为您提供 http 和 https url 来访问您的网络应用程序。

回答by vaishali chaudhari

  • To run https functionality or SSL authentication in flask application you first install "pyOpenSSL" python package using:

     pip install pyopenssl
    
  • Next step is to create 'cert.pem' and 'key.pem' using following command on terminal :

     openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
    
  • Copy generated 'cert.pem' and 'kem.pem' in you flask application project

  • Add ssl_context=('cert.pem', 'key.pem') in app.run()

  • 要在 Flask 应用程序中运行 https 功能或 SSL 身份验证,您首先使用以下命令安装“pyOpenSSL”python 包:

     pip install pyopenssl
    
  • 下一步是在终端上使用以下命令创建“cert.pem”和“key.pem”:

     openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
    
  • 在您的烧瓶应用程序项目中复制生成的“cert.pem”和“kem.pem”

  • 在 app.run() 中添加 ssl_context=('cert.pem', 'key.pem')

For example:

例如:

    from flask import Flask, jsonify

    app = Flask(__name__)

    @app.route('/')

    def index():

        return 'Flask is running!'


    @app.route('/data')

    def names():

        data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}

        return jsonify(data)

  if __name__ == '__main__':

        app.run(ssl_context=('cert.pem', 'key.pem'))

回答by Everett Toews

For a quick n' dirty self-signed cert, you can also use flask run --cert adhocor set the FLASK_RUN_CERTenv var.

对于快速的脏自签名证书,您还可以使用flask run --cert adhoc或设置FLASK_RUN_CERTenv var。

$ export FLASK_APP="app.py"
$ export FLASK_ENV=development
$ export FLASK_RUN_CERT=adhoc

$ flask run
 * Serving Flask app "app.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on https://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 329-665-000

The adhocoption isn't well documented (for good reason, never do this in production), but it's mentioned in the cli.py source code.

adhoc选项没有很好的文档记录(有充分的理由,永远不要在生产中这样做),但在cli.py 源代码 中提到了它。

There's a thorough explanation of this by Miguel Grinbergat Running Your Flask Application Over HTTPS.

Miguel GrinbergRunning Your Flask Application Over HTTPS中对此进行了彻底的解释。