Make Flask's url_for use the 'https' scheme in an AWS load balancer without messing with SSLify

后端 未结 2 973
梦谈多话
梦谈多话 2020-12-25 12:43

I\'ve recently added a SSL certificate to my webapp. It\'s deployed on Amazon Web Services uses load balancers. The load balancers work as reverse proxies, handling external

2条回答
  •  轮回少年
    2020-12-25 12:51

    Digging around Flask source code, I found out that url_for uses the Flask._request_ctx_stack.top.url_adapter when there is a request context.

    The url_adapter.scheme defines the scheme used. To make the _scheme parameter work, url_for will swap the url_adapter.scheme temporarily and then set it back before the function returns.

    (this behavior has been discussed on github as to whether it should be the previous value or PREFERRED_URL_SCHEME)

    Basically, what I did was set url_adapter.scheme to https with a before_request handler. This way doesn't mess with the request itself, only with the thing generating the urls.

    def _force_https():
        # my local dev is set on debug, but on AWS it's not (obviously)
        # I don't need HTTPS on local, change this to whatever condition you want.
        if not app.debug: 
            from flask import _request_ctx_stack
            if _request_ctx_stack is not None:
                reqctx = _request_ctx_stack.top
                reqctx.url_adapter.url_scheme = 'https'
    
    app.before_request(_force_https)
    

提交回复
热议问题