Login

Preferred Domain decorator function.

Author:
jamiecURLe
Posted:
November 25, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

From time to time I often have to work with a site that has two domain names. This can be an issue when dealing with mapping api keys so to solve this problem I whipped up a decorator function that allows a preferred domain to be enforced on a per view basis.

It wouldn't be too much to take this onto a middleware, but for my usage I just wanted a per view granularity and a decorator function suited my needs quite nicely.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.http import HttpResponse,  HttpResponseRedirect
from django.contrib.sites.models import Site

def prefered_domain(fn):
    """
    Allows for a preferred domain name to be enforced on a per_view basis
    if no domain is found, it fails silently.
    """
    def _prefered_domain(request, site_id=1):
        try:
            site = Site.objects.get(id=site_id)
            if request.META['HTTP_HOST'] not in site.domain:
                return HttpResponseRedirect('http://%s%s' % (site.domain, request.META['PATH_INFO']) )
        except Site.DoesNotExist:
            pass
        return fn(request)
    return _prefered_domain

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.