python flask redirect to https from http python flask redirect to https from http flask flask

python flask redirect to https from http


To me, it appears you're making it more complicated than it needs to be. Here is the code I use in my views.py script to force user to HTTPS connections:

@app.before_requestdef before_request():    if not request.is_secure:        url = request.url.replace('http://', 'https://', 1)        code = 301        return redirect(url, code=code)


According with the docs, after pip install Flask-SSLify you only need to insert the following code:

from flask import Flaskfrom flask_sslify import SSLifyapp = Flask(__name__)sslify = SSLify(app)

I have done it and it works very well. Am I missing something in the discussion ?


The Flask Security Guide recommends using Flask-Talisman.

$ pip install flask-talisman

Usage example:

from flask import Flaskfrom flask_talisman import Talismanapp = Flask(__name__)Talisman(app)

It forces HTTPS by default (from the README):

force_https, default True, forces all non-debug connects to https.


Personally, I got some errors relating to CSP (Content Security Policy) which I disabled with:

Talisman(app, content_security_policy=None)

But use this at your own risk :)