| 1 |
"""Deferred (lazy) imports for heavyweight optional dependencies. |
| 2 |
|
| 3 |
Importing ``jwt`` and ``cryptography`` at boot costs ~8MB of RSS, yet many |
| 4 |
deployments configure providers in settings without ever verifying a token |
| 5 |
(Celery workers, admin-only services, ...). Rather than sprinkling function |
| 6 |
local ``import jwt`` statements around the codebase -- which is easy to |
| 7 |
regress, since a single stray top-level ``import jwt`` silently negates the |
| 8 |
saving -- modules import these proxies once, at the top, and use them exactly |
| 9 |
as they would the real module:: |
| 10 |
|
| 11 |
from allauth.core.internal.deferred import jwt |
| 12 |
|
| 13 |
def verify(token, key): |
| 14 |
return jwt.decode(token, key, algorithms=["RS256"]) |
| 15 |
|
| 16 |
The underlying module (and any submodule accessed through it) is not imported |
| 17 |
until the first attribute access, which happens the first time a token is |
| 18 |
actually processed -- well after boot. |
| 19 |
""" |
| 20 |
|
| 21 |
from __future__ import annotations |
| 22 |
|
| 23 |
import importlib |
| 24 |
import importlib.util |
| 25 |
from types import ModuleType |
| 26 |
from typing import TYPE_CHECKING, Any |
| 27 |
|
| 28 |
|
| 29 |
class LazyModule: |
| 30 |
"""A stand-in for a module that imports the real thing on first use. |
| 31 |
|
| 32 |
Attribute access resolves against the real module once loaded. Missing |
| 33 |
attributes that name an importable submodule (e.g. |
| 34 |
``cryptography.hazmat``) resolve to a nested :class:`LazyModule`, so deep |
| 35 |
chains such as ``cryptography.hazmat.primitives.serialization`` stay lazy |
| 36 |
all the way down. |
| 37 |
""" |
| 38 |
|
| 39 |
def __init__(self, name: str) -> None: |
| 40 |
object.__setattr__(self, "_lazy_name", name) |
| 41 |
object.__setattr__(self, "_lazy_module", None) |
| 42 |
|
| 43 |
def _resolve(self) -> ModuleType: |
| 44 |
module = object.__getattribute__(self, "_lazy_module") |
| 45 |
if module is None: |
| 46 |
module = importlib.import_module( |
| 47 |
object.__getattribute__(self, "_lazy_name") |
| 48 |
) |
| 49 |
object.__setattr__(self, "_lazy_module", module) |
| 50 |
return module |
| 51 |
|
| 52 |
def __getattr__(self, attr: str) -> Any: |
| 53 |
# __getattr__ only fires for names not found the normal way, so it |
| 54 |
# never shadows _resolve/_lazy_* which live in the instance/class dict. |
| 55 |
module = self._resolve() |
| 56 |
try: |
| 57 |
return getattr(module, attr) |
| 58 |
except AttributeError: |
| 59 |
name = object.__getattribute__(self, "_lazy_name") |
| 60 |
full = f"{name}.{attr}" |
| 61 |
if importlib.util.find_spec(full) is not None: |
| 62 |
return LazyModule(full) |
| 63 |
raise |
| 64 |
|
| 65 |
def __repr__(self) -> str: |
| 66 |
name = object.__getattribute__(self, "_lazy_name") |
| 67 |
loaded = object.__getattribute__(self, "_lazy_module") is not None |
| 68 |
state = "loaded" if loaded else "deferred" |
| 69 |
return f"<LazyModule {name!r} ({state})>" |
| 70 |
|
| 71 |
|
| 72 |
if TYPE_CHECKING: |
| 73 |
# Type checkers bind these names to the real modules, so call sites get |
| 74 |
# the actual signatures -- and can annotate with e.g. |
| 75 |
# ``cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey`` -- while |
| 76 |
# importing nothing at runtime. Submodules are spelled out because an |
| 77 |
# ``import cryptography`` alone does not make them resolvable. |
| 78 |
import cryptography.hazmat.backends |
| 79 |
import cryptography.hazmat.primitives.asymmetric.rsa |
| 80 |
import cryptography.hazmat.primitives.ciphers |
| 81 |
import cryptography.hazmat.primitives.serialization |
| 82 |
import cryptography.x509 |
| 83 |
import jwt |
| 84 |
import jwt.algorithms |
| 85 |
import jwt.exceptions |
| 86 |
else: |
| 87 |
jwt = LazyModule("jwt") |
| 88 |
cryptography = LazyModule("cryptography") |