Debian Codegraph @

django/contrib/sites/models.py

raw
1 import string
2
3 from django.core.exceptions import ImproperlyConfigured, ValidationError
4 from django.db import models
5 from django.db.models.signals import pre_delete, pre_save
6 from django.http.request import split_domain_port
7 from django.utils.translation import gettext_lazy as _
8
9 SITE_CACHE = {}
10
11
12 def _simple_domain_name_validator(value):
13 """
14 Validate that the given value contains no whitespaces to prevent common
15 typos.
16 """
17 checks = ((s in value) for s in string.whitespace)
18 if any(checks):
19 raise ValidationError(
20 _("The domain name cannot contain any spaces or tabs."),
21 code="invalid",
22 )
23
24
25 class SiteManager(models.Manager):
26 use_in_migrations = True
27
28 def _get_site_by_id(self, site_id):
29 if site_id not in SITE_CACHE:
30 site = self.get(pk=site_id)
31 SITE_CACHE[site_id] = site
32 return SITE_CACHE[site_id]
33
34 def _get_site_by_request(self, request):
35 host = request.get_host()
36 try:
37 # First attempt to look up the site by host with or without port.
38 if host not in SITE_CACHE:
39 SITE_CACHE[host] = self.get(domain__iexact=host)
40 return SITE_CACHE[host]
41 except Site.DoesNotExist:
42 # Fallback to looking up site after stripping port from the host.
43 domain, port = split_domain_port(host)
44 if domain not in SITE_CACHE:
45 SITE_CACHE[domain] = self.get(domain__iexact=domain)
46 return SITE_CACHE[domain]
47
48 def get_current(self, request=None):
49 """
50 Return the current Site based on the SITE_ID in the project's settings.
51 If SITE_ID isn't defined, return the site with domain matching
52 request.get_host(). The ``Site`` object is cached the first time it's
53 retrieved from the database.
54 """
55 from django.conf import settings
56
57 if getattr(settings, "SITE_ID", ""):
58 site_id = settings.SITE_ID
59 return self._get_site_by_id(site_id)
60 elif request:
61 return self._get_site_by_request(request)
62
63 raise ImproperlyConfigured(
64 'You\'re using the Django "sites framework" without having '
65 "set the SITE_ID setting. Create a site in your database and "
66 "set the SITE_ID setting or pass a request to "
67 "Site.objects.get_current() to fix this error."
68 )
69
70 def clear_cache(self):
71 """Clear the ``Site`` object cache."""
72 global SITE_CACHE
73 SITE_CACHE = {}
74
75 def get_by_natural_key(self, domain):
76 return self.get(domain=domain)
77
78
79 class Site(models.Model):
80 domain = models.CharField(
81 _("domain name"),
82 max_length=100,
83 validators=[_simple_domain_name_validator],
84 unique=True,
85 )
86 name = models.CharField(_("display name"), max_length=50)
87
88 objects = SiteManager()
89
90 class Meta:
91 db_table = "django_site"
92 verbose_name = _("site")
93 verbose_name_plural = _("sites")
94 ordering = ["domain"]
95
96 def __str__(self):
97 return self.domain
98
99 def natural_key(self):
100 return (self.domain,)
101
102
103 def clear_site_cache(sender, **kwargs):
104 """
105 Clear the cache (if primed) each time a site is saved or deleted.
106 """
107 instance = kwargs["instance"]
108 using = kwargs["using"]
109 try:
110 del SITE_CACHE[instance.pk]
111 except KeyError:
112 pass
113 try:
114 del SITE_CACHE[Site.objects.using(using).get(pk=instance.pk).domain]
115 except (KeyError, Site.DoesNotExist):
116 pass
117
118
119 pre_save.connect(clear_site_cache, sender=Site)
120 pre_delete.connect(clear_site_cache, sender=Site)