from asgiref.sync import sync_to_async from django.http import Http404 from django.utils.deprecation import MiddlewareMixin from django_scopes import scope from scopedsites.models import Domain class DomainScopeMiddleware(MiddlewareMixin): async def __acall__(self, request): d = await sync_to_async(Domain.get_from_request)(request) with scope(domain=d): return await super().__acall__(request) def __call__(self, request): if self._is_coroutine: return super().__call__(request) d = Domain.get_from_request(request) with scope(domain=d): return super().__call__(request) class DomainAutoCreateMiddleware(MiddlewareMixin): def __init__(self, get_response): super().__init__(get_response) self.cache = set() def process_request(self, r): if (host := r.META.get("HTTP_HOST")) in self.cache: return try: Domain.get_from_request(r) self.cache.add(host) except Http404: Domain.objects.create(fqdn=r.META.get('HTTP_HOST'))