在Flask Python中使用Http的Https

2024-05-17 03:42:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

    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)

现在我想使用http和https来运行服务器。有可能的办法吗?


Tags: topathkeyhttpsssl客户机certuse
2条回答

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

我最近也遇到过类似的问题。为了测试在将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)

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

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

相关问题 更多 >