Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

SSL for particular views

Posted by Dmitry Chaplinsky on 2012-05-18 @ 21:30 and filed in Decorators

Sometime you want to enable https only for some of ulrs on your website. For example, login, registration, checkout etc.

In this case you can use decorator like this:

from functools import wraps
from flask import request, redirect, current_app

def ssl_required(fn):
    def decorated_view(*args, **kwargs):
        if current_app.config.get("SSL"):
            if request.is_secure:
                return fn(*args, **kwargs)
                return redirect(request.url.replace("http://", "https://"))
        return fn(*args, **kwargs)
    return decorated_view

This snippet by Dmitry Chaplinsky can be used freely for anything you like. Consider it public domain.