Login

Decorator to modify reverse() to render SSL urls

Author:
AndrewIngram
Posted:
April 27, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This snippet monkey-patches Django's reverse() method (use for generating URLs from vew functions and parameters) to allow certain areas of your site to automatically have URLs with the correct SSL domain in place.

This saves you from having to use unnecessary redirects to guide users to an SSL-encrypted version of a page. This should still be used alongside a redirect-based method (such as this snippet) to ensure that the user can't access an unencrypted version of the page

Simply add the code to the files mentioned in the code.

This obviously won't work anywhere that doesn't use reverse(), the admin app seems to be an example of this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
In your site's __init__.py
"""

from django.core import urlresolvers
from django.conf import settings

def reverse_decorator(func):
    def inner(*args, **kwargs):
        abs_path = func(*args,**kwargs)
        if settings.SSL_DOMAIN and settings.SSL_SECTIONS and settings.SSL_DOMAIN.startswith('https'):
            for section in settings.SSL_SECTIONS:
                if abs_path.startswith(section):
                    abs_path = settings.SSL_DOMAIN + abs_path
                    break
        return abs_path        
    return inner
urlresolvers.reverse = reverse_decorator(urlresolvers.reverse)

"""
In settings.py
"""

SSL_DOMAIN = 'https://example.com'
            
SSL_SECTIONS = (
    '/checkout',
    '/account',
)

More like this

  1. A wrapper around cache_page making it optional by rixx 2 days, 6 hours ago
  2. Treat empty value on DateRangeFilter as a filter for non filled dates by kmmbvnr 1 month, 1 week ago
  3. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 months, 1 week ago
  4. codigo alto nivel by MrRocklion 4 months, 1 week ago
  5. Load template from specific app by Krzysiek555 4 months, 4 weeks ago

Comments

Please login first before commenting.