Skip to content

Commit

Permalink
Change AXES_COOLOFF_TIME callable to take exactly 1 argument
Browse files Browse the repository at this point in the history
  • Loading branch information
browniebroke authored and aleksihakli committed Oct 2, 2024
1 parent 8ed0d82 commit b54019f
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 15 deletions.
16 changes: 3 additions & 13 deletions axes/helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import functools
import inspect
from datetime import timedelta
from hashlib import sha256
from logging import getLogger
Expand Down Expand Up @@ -58,7 +56,7 @@ def get_cool_off(request: Optional[HttpRequest] = None) -> Optional[timedelta]:
The return value is either None or timedelta.
Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, integer/float of hours,
a path to a callable or a callable taking zero or 1 argument (the request). This function
a path to a callable or a callable taking 1 argument (the request). This function
offers a unified _timedelta or None_ representation of that configuration for use with the
Axes internal implementations.
Expand All @@ -73,21 +71,13 @@ def get_cool_off(request: Optional[HttpRequest] = None) -> Optional[timedelta]:
return timedelta(minutes=cool_off * 60)
if isinstance(cool_off, str):
cool_off_func = import_string(cool_off)
return _maybe_partial(cool_off_func, request)()
return cool_off_func(request)
if callable(cool_off):
return _maybe_partial(cool_off, request)() # pylint: disable=not-callable
return cool_off(request) # pylint: disable=not-callable

return cool_off


def _maybe_partial(func: Callable, request: Optional[HttpRequest] = None):
"""Bind the given request to the function if it accepts a single argument."""
sig = inspect.signature(func)
if len(sig.parameters) == 1:
return functools.partial(func, request)
return func


def get_cool_off_iso8601(delta: timedelta) -> str:
"""
Return datetime.timedelta translated to ISO 8601 formatted duration for use in e.g. cool offs.
Expand Down
4 changes: 2 additions & 2 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -947,7 +947,7 @@ def test_get_lockout_response_lockout_response(self):
self.assertEqual(type(response), HttpResponse)


def mock_get_cool_off_str():
def mock_get_cool_off_str(req):
return timedelta(seconds=30)


Expand All @@ -972,7 +972,7 @@ def test_get_cool_off_float_lt_0(self):
def test_get_cool_off_float_gt_0(self):
self.assertEqual(get_cool_off(), timedelta(seconds=6120))

@override_settings(AXES_COOLOFF_TIME=lambda: timedelta(seconds=30))
@override_settings(AXES_COOLOFF_TIME=lambda r: timedelta(seconds=30))
def test_get_cool_off_callable(self):
self.assertEqual(get_cool_off(), timedelta(seconds=30))

Expand Down

0 comments on commit b54019f

Please sign in to comment.