python flask从http重定向到https

问题描述:

我有一个使用 python3.4 和 Flask 构建的网站...我已经生成了自己的自签名证书,目前我正在通过 localhost 测试我的网站.

I have a website build using python3.4 and flask...I have generated my own self-signed certificate and I am currently testing my website through localhost.

我正在使用 python ssl 模块和这个烧瓶扩展:https://github.com/kennethreitz/flask-sslify

I am using the python ssl module along with this flask extension: https://github.com/kennethreitz/flask-sslify

context = ('my-cert.pem', 'my-key.pem')
app = Flask(__name__)
sslify = SSLify(app)

...

if __name__ == '__main__':
    app.debug = False
    app.run(
    host="127.0.0.1",
    port=int("5000"),
    ssl_context=context
)

然而,这似乎不起作用.我查看了 sslify 源代码,这一行似乎不起作用

This does not seem to be working however. I took a look in the sslify source code and this line does not seem to be working

def init_app(self, app):
    """Configures the configured Flask app to enforce SSL."""
    app.before_request(self.redirect_to_ssl)
    app.after_request(self.set_hsts_header)

特别是redirect_to_ssl的函数调用(我在redirect_to_ssl函数下添加了我自己的打印语句,我的语句从未打印过)

Specifically the function call to redirect_to_ssl (I added my own print statement under the redirect_to_ssl function and my statement was never printed)

def redirect_to_ssl(self):
    print("THIS IS WORKING")
    """Redirect incoming requests to HTTPS."""
    Should we redirect?
    criteria = [
        request.is_secure,
        current_app.debug,
        request.headers.get('X-Forwarded-Proto', 'http') == 'https'
    ]

    if not any(criteria) and not self.skip:
        if request.url.startswith('http://'):
            url = request.url.replace('http://', 'https://', 1)
            code = 302
            if self.permanent:
                code = 301
            r = redirect(url, code=code)
            return r

我对 python 很陌生.有什么想法吗?

I am pretty new to python. Any ideas?

在我看来,你让它变得比实际需要的更复杂.这是我在 views.py 脚本中用于强制用户使用 HTTPS 连接的代码:

To me, it appears you're making it more complicated than it needs to be. Here is the code I use in my views.py script to force user to HTTPS connections:

@app.before_request
def before_request():
    if not request.is_secure:
        url = request.url.replace('http://', 'https://', 1)
        code = 301
        return redirect(url, code=code)