Skip to content

Instantly share code, notes, and snippets.

@ckinsey
Created March 22, 2014 16:34
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ckinsey/9709984 to your computer and use it in GitHub Desktop.
Save ckinsey/9709984 to your computer and use it in GitHub Desktop.
Require SSL for Django views via a decorator. You'll need some setup in your web server to support the request.is_secure() method--see the Django docs.
from functools import wraps
from django.conf import settings
from django.http import HttpResponseRedirect
def require_ssl(view):
"""
Decorator that requires an SSL connection. If the current connection is not SSL, we redirect to the SSL version of
the page.
"""
@wraps(view)
def wrapper(request, *args, **kwargs):
if not settings.DEBUG and not request.is_secure():
# Redirect!
target_url = "https://" + request.META['HTTP_HOST'] + request.path_info
return HttpResponseRedirect(target_url)
return view(request, *args, **kwargs)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment