Adding https support in Flask

Posted by

Getting a chance to work on Python, my favorite framework is Flask ( It is a micro-framework that lets you create and deploy APIs, websites, and dashboards.

When deploying Flask projects onto a production server, we need to only support HTTPS and redirect HTTP requests to HTTPS. This creates a problem with Flask url_for function, which only outputs HTTP URLs.

Below is one way to achieve this. Following is taken from my production deployment.

import os
from flask import Flask

app = Flask(__name__)

def before_request():
    if os.environ["PROJECT_ENV"] != "dev":
        from flask import _request_ctx_stack
        if _request_ctx_stack is not None:
            reqctx =
            reqctx.url_adapter.url_scheme = "https"

if __name__ == "__main__":, host="")


Update: 8 June 2017

I have found another way of adding https support to flask.

from flask import Flask

class ReverseProxied(object):
        def __init__(self, app):
       = app

        def __call__(self, environ, start_response):
                environ['wsgi.url_scheme'] = 'https'
                return, start_response)

app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)

if __name__ == "__main__":, host="")

This was mentioned in stack overflow post:

Let me know if you have a better approach to this problem.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s