Ticket #4438: get_from_host.patch
File get_from_host.patch, 2.9 KB (added by , 17 years ago) |
---|
-
django/contrib/sites/middleware.py
1 class LazySite(object): 2 def __get__(self, request, obj_type=None): 3 if not hasattr(request, '_cached_site'): 4 from django.contrib.sites.models import Site 5 request._cached_site = Site.get_from_host(request) 6 return request._cached_site 7 8 class CurrentSiteMiddleware(object): 9 def process_request(self, request): 10 request.__class__.site = LazySite() 11 return None -
django/contrib/sites/models.py
6 6 class SiteManager(models.Manager): 7 7 def get_current(self): 8 8 """ 9 Returns the current ``Site`` based on the SITE_ID in the 10 project's settings. The ``Site`` object is cached the first11 time it's retrievedfrom the database.9 Returns the current ``Site`` based on the SITE_ID in the project's 10 settings. The ``Site`` object is cached the first time it's retrieved 11 from the database. 12 12 """ 13 13 from django.conf import settings 14 14 try: … … 28 28 global SITE_CACHE 29 29 SITE_CACHE = {} 30 30 31 def get_from_host(self, request, check_subdomain=True): 32 """ 33 Returns the ``Site`` which matches the host name retreived from 34 ``request``. 35 36 If no match is found and ``check_subdomain`` is ``True``, the sites are 37 searched again for sub-domain matches. 38 39 If still no match, or if more than one ``Site`` matched the host name, a 40 ``RequestSite`` object is returned. 41 42 The returned ``Site`` or ``RequestSite`` object is cached for the host 43 name retrieved from ``request``. 44 """ 45 host = request.get_host().lower() 46 if host in SITE_CACHE: 47 # The host name was found in cache, return it 48 return SITE_CACHE[host] 49 matches = Site.objects.filter(domain__iexact=host) 50 # We use len rather than count to save a second query if there was only 51 # one matching Site 52 count = len(matches) 53 if not count and check_subdomain: 54 matches = [] 55 for site in Site.objects.all(): 56 if host.endswith(site.domain.lower()): 57 matches.append(site) 58 count = len(matches) 59 if count == 1: 60 # Return the single matching Site 61 return matches[0] 62 # Fall back to just using a RequestSite 63 return RequestSite(request) 64 31 65 class Site(models.Model): 32 66 domain = models.CharField(_('domain name'), max_length=100) 33 67 name = models.CharField(_('display name'), max_length=50)