我正在使用Python Flask爲IBM的Bluemix編寫一個應用程序。我想強制入站請求爲https。這段代碼的作品:使用Flask的before_request強制使用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()
。
燒瓶文檔狀態:
的功能將被稱爲不帶任何參數。如果該函數返回非None值,則將其視爲來自視圖的返回值,並且進一步的請求處理已停止。
我認爲這意味着如果我返回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
塊。我的失敗是否與我的執行有關,對Flask的理解是什麼?
簽出此擴展程序:https://github.com/kennethreitz/flask-sslify – AArias