在 Flask Python 中使用 Https

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

Https with Http in Flask Python

pythonhttphttpsflask

提问by Yasmin Reda

I have a client server application. I managed to make them connect over https using SSl encryption using this

我有一个客户端服务器应用程序。我设法使他们使用这个使用 SSl 加密通过 https 连接

    context = SSL.Context(SSL.SSLv3_METHOD)
    context.use_privatekey_file('/path_to_key/key.key')
    context.use_certificate_file('/path_to_cert/cert.crt')
    app.run(use_reloader=True, host='0.0.0.0',port=9020,ssl_context = context)

Now I want to run the server using both http and https. Is there any possible way to do that?

现在我想同时使用 http 和 https 运行服务器。有没有办法做到这一点?

采纳答案by Tritium21

First big thing: don't use the built in web server in flask to do any heavy lifting. You should use a real web server like apache (mod_wsgi) nginex + gunicore, etc. These servers have documentation on how to run http and https simultaneously.

第一件大事:不要使用 Flask 中的内置 Web 服务器来做任何繁重的工作。您应该使用真正的网络服务器,如 apache (mod_wsgi) nginex + gunicore 等。这些服务器有关于如何同时运行 http 和 https 的文档。

回答by John Drefahl

My I suggest trying out Flask-SSLify- https://github.com/kennethreitz/flask-sslify

我建议尝试Flask-SSLify- https://github.com/kennethreitz/flask-sslify

Usage

用法

Usage is pretty simple:

用法非常简单:

from flask import Flask
from flask_sslify import SSLify

app = Flask(__name__)
sslify = SSLify(app)

If you make an HTTP request, it will automatically redirect:

如果您发出 HTTP 请求,它将自动重定向:

$ curl -I http://secure-samurai.herokuapp.com/
HTTP/1.1 302 FOUND
Content-length: 281
Content-Type: text/html; charset=utf-8
Date: Sun, 29 Apr 2012 21:39:36 GMT
Location: https://secure-samurai.herokuapp.com/
Server: gunicorn/0.14.2
Strict-Transport-Security: max-age=31536000
Connection: keep-alive

Install

安装

Installation is simple too:

安装也很简单:

$ pip install Flask-SSLify

回答by jfs

Now i want to run the server using both http and https is there any possible way to do that ??

现在我想同时使用 http 和 https 运行服务器有什么可能的方法吗??

I have had a similar problem recently. To test whether a proxy is used after http is redirected to https, I've just started two processes on different ports: one for http, another for https:

我最近遇到了类似的问题。为了测试在 http 重定向到 https 后是否使用代理,我刚刚在不同的端口上启动了两个进程:一个用于 http,另一个用于 https:

#!/usr/bin/env python3
"""Serve both http and https. Redirect http to https."""
from flask import Flask, abort, redirect, request # $ pip install flask

app = Flask(__name__)

@app.route('/')
def index():
    if request.url.startswith('http://'):
        return redirect(request.url.replace('http', 'https', 1)
                        .replace('080', '443', 1))
    elif request.url.startswith('https://'):
        return 'Hello HTTPS World!'
    abort(500)

def https_app(**kwargs):
    import ssl
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.load_cert_chain('server.crt', 'server.key')
    app.run(ssl_context=context, **kwargs)


if __name__ == "__main__":
    from multiprocessing import Process

    kwargs = dict(host='localhost')
    Process(target=https_app, kwargs=dict(kwargs, port=7443),
            daemon=True).start()
    app.run(port=7080, **kwargs)

Needless to say, it is only for testing/debugging purposes.

不用说,它仅用于测试/调试目的。

回答by Jammooly

I've ran into trouble with this also. I originally had:

我也遇到了这个问题。我原来有:

    if sys.argv[1] == 'https' or sys.argv[1] == 'Https':
        app.run(host="0.0.0.0", port=12100, ssl_context='adhoc')
    elif sys.argv[1] == 'http' or sys.argv[1] == 'HTTP':
        app.run(host="0.0.0.0", port=12100)

which only allowed either http or https at a time and not both.

一次只允许 http 或 https 而不是两者都允许。

So I used multi-threading to make both work at the same time. I put each app.run in it's own function and called an independent thread on each one of them.

所以我使用多线程让两者同时工作。我把每个 app.run 放在它自己的函数中,并在每个函数上调用一个独立的线程。

import threading
import time as t

...

def runHttps():
    app.run(host="0.0.0.0", port=12101, ssl_context='adhoc')

def runHttp():
    app.run(host="0.0.0.0", port=12100)

if __name__ == '__main__':
    # register_views(app)
    CORS(app, resources={r"*": {"origins": "*"}}, supports_credentials=True)
    if sys.argv[1] == 'https' or sys.argv[1] == 'Https' or sys.argv[1] == 'http' or sys.argv[1] == 'Http':
        print("here")
        y = threading.Thread(target=runHttp)
        x = threading.Thread(target=runHttps)
        print("before running runHttps and runHttp")
        y.start()
        t.sleep(0.5)
        x.start()

And that's how I made http and https work at the same time.

这就是我让 http 和 https 同时工作的方式。