繁体   English   中英

在 Flask Python 中使用 Https

[英]Https with Http in Flask Python

我有一个客户端服务器应用程序。 我设法使他们使用这个使用 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)

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

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

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

用法

用法非常简单:

from flask import Flask
from flask_sslify import SSLify

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

如果您发出 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

安装

安装也很简单:

$ pip install Flask-SSLify

现在我想同时使用 http 和 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)

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

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

    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)

一次只允许使用 http 或 https,而不能同时允许。

所以我使用多线程让两者同时工作。 我把每个 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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM