Skip to main content
 首页 » 编程设计

python之通过 Flask 的 before_request() 强制使用 HTTPS

2025年02月15日7dyllove98

我正在使用 Python Flask 为 IBM 的 Bluemix 编写应用程序。我想强制入站请求为 https。这段代码有效:

# We want to redirect the request to use https. X-Forwarded-Proto is only set in Bluemix runtime.  
forwarded_protocol = request.headers.get('X-Forwarded-Proto', None) 
if forwarded_protocol is not None: 
    if forwarded_protocol == 'http': 
        new_url = request.url.replace('http', 'https', 1) 
        return redirect(new_url) 

我不想把它放在我的每个路由定义中,而是想在一个地方做。根据 Flask 文档,我想我想要的是使用 before_request()。

Flask 文档指出:

The function will be called without any arguments. If the function returns a non-None value, it’s handled as if it was the return value from the view and further request handling is stopped.

我认为这意味着如果我返回 None,处理将继续使用请求的路由代码。所以我的实现看起来像:

@app.before_request 
def force_https(): 
    # We want to redirect the request to use https. X-Forwarded-Proto is only set in Bluemix runtime.  
    try: 
        forwarded_protocol = request.headers.get('X-Forwarded-Proto', None) 
        if forwarded_protocol is not None: 
            if forwarded_protocol == 'http': 
                new_url = request.url.replace('http', 'https', 1) 
                return redirect(new_url) 
            else: 
                return None 
        else: 
            return None 
    except RuntimeError as e: 
        return None 

很明显,我的实现或理解有问题。在此方法运行到路由代码后,我无法交出控制权。并且 before_request() 也似乎在 Flask 启动时被调用,在第一个请求之前,因此 try/except block 。我的失败是否与我的实现、对 Flask 的理解有关?

请您参考如下方法:

您可以检查请求端点是否是 View 函数之一,以避免运行时错误。 return None 在技术上等同于 return,但如果您什么都不做,python 中的函数会自动返回 None。确保将“http://”替换为“https://”而不仅仅是“http”,因为字符串“http”可以出现在 URL 中的任何其他位置。与检查 X-Forwarded-Proto header 相比,request.is_secure 可能是检查请求是否安全的更好方法。请尝试以下操作:

@app.before_request 
def force_https(): 
    if request.endpoint in app.view_functions and not request.is_secure: 
        return redirect(request.url.replace('http://', 'https://')) 

您还可以创建自己的装饰器来重定向非安全请求。例如,请参见此片段:http://flask.pocoo.org/snippets/93/ .