Bootstrap FreeKB - Flask - Force HTTP to redirect to HTTPS
Flask - Force HTTP to redirect to HTTPS

Updated:   |  Flask articles

The following function can be used to force all routes in your view to be redirected to HTTPS.

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

 

Or, the Flask Security Guide recommends using Flask-Talisman. The pip install command can be used to install flask-talisman.

pip install flask-talisman

 

Or, you can specify the version to install

pip install flask-talisman==1.0.0

 

Or, better yet, use a requirements.txt file.

flask-talisman==1.0.0

 

And then install the packages using the requirements.txt file.

pip install --requirement requirements.txt

 

In your controller, import flask_talisman can then use the Talisman module to force HTTPS

from flask import Flask
from flask_talisman import Talisman

app = Flask(__name__)
Talisman(app)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 378388 in the box below so that we can be sure you are a human.