| | 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. A cache value |
| | 48 | # of None means that a RequestSite should just be used. |
| | 49 | return SITE_CACHE[host] or RequestSite(request) |
| | 50 | matches = Site.objects.filter(domain__iexact=host) |
| | 51 | # We use len rather than count to save a second query if there was only |
| | 52 | # one matching Site |
| | 53 | count = len(matches) |
| | 54 | if not count and check_subdomain: |
| | 55 | matches = [] |
| | 56 | for site in Site.objects.all(): |
| | 57 | if host.endswith(site.domain.lower()): |
| | 58 | matches.append(site) |
| | 59 | count = len(matches) |
| | 60 | if count == 1: |
| | 61 | # Return the single matching Site |
| | 62 | site = matches[0] |
| | 63 | else: |
| | 64 | site = None |
| | 65 | # Cache the site (caching None means we should use RequestSite). |
| | 66 | SITE_CACHE[host] = site |
| | 67 | # Return site, falling back to just using a RequestSite. |
| | 68 | return site or RequestSite(request) |
| | 69 | |