Adding https support in Flask

Getting a chance to work on Python, my favorite framework is Flask (http://flask.pocoo.org/). 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__)

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

if __name__ == "__main__":
    app.run(port=80, host="0.0.0.0")

 

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):
                self.app = app

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

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

if __name__ == "__main__":
    app.run(port=80, host="0.0.0.0")

This was mentioned in stack overflow post:

https://stackoverflow.com/a/37842465

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

2 thoughts on “Adding https support in Flask”

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s