我在负载平衡后面有一个终止 SSL 的 Flask 应用程序。我有代码可以“检测”何时使用 SSL 并改变请求对象:
@app.before_request
def before_request():
x_forwarded_proto = request.headers.get('X-Forwarded-Proto')
if x_forwarded_proto == 'https':
request.url = request.url.replace('http://', 'https://')
request.url_root = request.url_root.replace('http://', 'https://')
request.host_url = request.host_url.replace('http://', 'https://')
然后我有一个蓝图视图函数:
admin = Blueprint('admin', __name__, url_prefix='/admin')
@admin.route('/login')
def login():
print request.url
该函数的输出(当我转到 /admin/login 时)始终是 http:// 而不是 https:// (尽管它应该在before_request
功能。
关于如何解决这个问题有什么想法吗?
事实证明request
是一个代理对象。我不确定内部结构,但它在每次导入时都会“重置”。我通过子类化解决了这个问题Request
class ProxiedRequest(Request):
def __init__(self, environ, populate_request=True, shallow=False):
super(Request, self).__init__(environ, populate_request, shallow)
# Support SSL termination. Mutate the host_url within Flask to use https://
# if the SSL was terminated.
x_forwarded_proto = self.headers.get('X-Forwarded-Proto')
if x_forwarded_proto == 'https':
self.url = self.url.replace('http://', 'https://')
self.host_url = self.host_url.replace('http://', 'https://')
self.base_url = self.base_url.replace('http://', 'https://')
self.url_root = self.url_root.replace('http://', 'https://')
app = Flask(__name__);
app.request_class = ProxiedRequest
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)