简体   繁体   中英

Flask development server WSGI configuration

In production, my flask application is not run at the domain root, but instead at https://domain:port/app. HAproxy handles this and also terminates SSL. I would like to do the same using the flask development server, but am having issues with url_for and redirect . Namely, url_for is excluding /app and redirect(url_for(...)) ends up redirecting to http.

I understand that in production, the uWSGI config sets SCRIPT_NAME to /app to make url_for behave correctly. I believe it also does something to set wsgi.url_scheme to https , but am not sure.

Is there any way to set the WSGI config when running the dev server? All solutions I have seen involve things like custom middleware or ProxyFix, but then I have to do some sort of if switch to determine whether to apply these fixes, as they are unnecessary and break production. I am hoping there is a way to configure the WSGI environment with environment variables via the command line call to flask run so that both development and production are using the same code paths.

Thanks in advance!

Ended up writing a custom middleware to do the job. __init__.py :

class DevelopmentProxyFix():
    def __init__(self, app):
        self.app = app
    def __call__(self, environ, start_response):
        environ['SCRIPT_NAME'] = '/app'
        environ['wsgi.url_scheme'] = 'https'
        return self.app(environ, start_response)

def create_app():
    app = Flask(__name__)
    ...
    if app.config['ENV'] == "development":
        app.wsgi_app = DevelopmentProxyFix(app.wsgi_app)
    ...
    return app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM