在Flask + Heroku上将HTTP重定向到HTTPS

The*_*net 7 python https heroku flask

当我尝试将传入流量重定向到https时,我得到一个无限重定向循环.

@app.route('/checkout/')                                                                                                                                                                                        
def checkout():                                                                                                                                                                                                 
    checkout = "https://myapp.herokuapp.com/checkout/"                                                                                                                                              
    if checkout != request.url:                                                                                                                                                                             
        print checkout, request.url                                                                                                                                                                             
        return redirect(checkout)                                                                                                                                                                               
    return render_template('checkout.html', key=keys['publishable_key']) 
Run Code Online (Sandbox Code Playgroud)

request.url永远不会更改为前缀https.我想使用heroku的搭载ssl来降低成本.

Rya*_*yan 13

1)做"pip install flask-sslify"

(github在这里:https://github.com/kennethreitz/flask-sslify)

2)包括以下几行:

from flask_sslify import SSLify
if 'DYNO' in os.environ: # only trigger SSLify if the app is running on Heroku
    sslify = SSLify(app)
Run Code Online (Sandbox Code Playgroud)


fri*_*ism 6

在Heroku上,SSL(https)在到达您的应用程序之前终止,因此您的应用程序永远不会真正看到SSL流量.要检查是否使用https发出请求,您必须检查x-forwarded-proto标头.更多信息:如何在Heroku https上制作python?

更新:供您使用,您只需检查request.url"myapp.herokuapp.com/checkout/"; 并验证标头是"https"


Mil*_*les 5

我尝试了SSLify,url_for _scheme,并设置了PREFERRED_URL_SCHEME;但是,至少在发行版上没有一个解决方案。

@app.before_request
def beforeRequest():
    if not request.url.startswith('https'):
        return redirect(request.url.replace('http', 'https', 1))
Run Code Online (Sandbox Code Playgroud)

本质上,这是无需任何配置或扩展即可完成它的另一种方法。