Browse Source

read the docs (code)

main
Julia Luna 2 years ago
parent
commit
f2f4a770da
Signed by: xenua
GPG Key ID: 6A0C04FA9A7D7582
  1. 45
      scopedsites/middleware.py
  2. 2
      setup.py

45
scopedsites/middleware.py

@ -1,48 +1,25 @@
import asyncio
from django.http import Http404 from django.http import Http404
from django.utils.deprecation import MiddlewareMixin
from django_scopes import scope from django_scopes import scope
from scopedsites.models import Domain from scopedsites.models import Domain
class DomainScopeMiddleware: class DomainScopeMiddleware(MiddlewareMixin):
async_capable = True def __call__(self, request):
def __init__(self, get_response):
self.get_response = get_response
self.is_async = asyncio.iscoroutinefunction(get_response)
self.__call__ = self._ahandler if self.is_async else self._handler
async def _ahandler(self, request):
d = Domain.get_from_request(request) d = Domain.get_from_request(request)
with scope(domain=d): with scope(domain=d):
return await self.get_response(request) return super()(request)
def _handler(self, request):
d = Domain.get_from_request(request) # technically does hit the db layer, but should get caught in memcache
# TODO: performance testing
with scope(domain=d):
return self.get_response(request)
class DomainAutoCreateMiddleware: class DomainAutoCreateMiddleware(MiddlewareMixin):
async_capable = True
def __init__(self, get_response): def __init__(self, get_response):
self.get_response = get_response super().__init__(get_response)
self.is_async = asyncio.iscoroutinefunction(get_response)
self.__call__ = self._ahandler if self.is_async else self._handler
self.cache = set() self.cache = set()
def ensure_exists(self, r): def process_request(self, r):
if (host := r.META.get("HTTP_HOST")) in self.cache: if (host := r.META.get("HTTP_HOST")) in self.cache:
return return
@ -51,11 +28,3 @@ class DomainAutoCreateMiddleware:
self.cache.add(host) self.cache.add(host)
except Http404: except Http404:
Domain.objects.create(fqdn=r.META.get('HTTP_HOST')) Domain.objects.create(fqdn=r.META.get('HTTP_HOST'))
def _handler(self, req):
self.ensure_exists(req)
return self.get_response(req)
async def _ahandler(self, req):
self.ensure_exists(req)
return await self.get_response(req)

2
setup.py

@ -3,7 +3,7 @@ from setuptools import setup
setup( setup(
name="django_scopedsites", name="django_scopedsites",
packages=["scopedsites", "scopedsites.migrations"], packages=["scopedsites", "scopedsites.migrations"],
version="0.1.6", version="0.1.7",
description="django_scopes x django.contrib.sites", description="django_scopes x django.contrib.sites",
python_requires=">=3.6", python_requires=">=3.6",
install_requires=[ install_requires=[

Loading…
Cancel
Save