hooks.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """
  2. requests.hooks
  3. ~~~~~~~~~~~~~~
  4. This module provides the capabilities for the Requests hooks system.
  5. Available hooks:
  6. ``response``:
  7. The response generated from a Request.
  8. """
  9. from __future__ import annotations
  10. from collections.abc import Callable, Iterable
  11. from typing import TYPE_CHECKING, Any
  12. if TYPE_CHECKING:
  13. from . import _types as _t
  14. from .models import Response
  15. HOOKS: list[str] = ["response"]
  16. def default_hooks() -> dict[str, list[_t.HookType]]:
  17. return {event: [] for event in HOOKS}
  18. # TODO: response is the only one
  19. def dispatch_hook(
  20. key: str,
  21. hooks: _t.HooksInputType | None,
  22. hook_data: Response,
  23. **kwargs: Any,
  24. ) -> Response:
  25. """Dispatches a hook dictionary on a given piece of data."""
  26. hooks_dict = hooks or {}
  27. hook_list: Iterable[_t.HookType] | _t.HookType | None = hooks_dict.get(key)
  28. if hook_list:
  29. if isinstance(hook_list, Callable):
  30. hook_list = [hook_list]
  31. for hook in hook_list:
  32. _hook_data = hook(hook_data, **kwargs)
  33. if _hook_data is not None:
  34. hook_data = _hook_data
  35. return hook_data