From 7f5833ac21880bb9790ad04d2c892cb146884428 Mon Sep 17 00:00:00 2001 From: mizvyt Date: Tue, 1 Oct 2019 19:46:30 +0800 Subject: [PATCH] Addressed review comments --- docs/api-guide/throttling.md | 2 +- rest_framework/throttling.py | 3 ++- tests/test_throttling.py | 10 ++++++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 54a0b6ca4..4a1693f4a 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -41,7 +41,7 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C } } -The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. To set the rate to a fraction of a period, simply prepend the desired timespan. For example, a rate of `'100/30s'` will mean "limit requests to a maximum of 100 per every 30 seconds". +The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. The throttle period can optionally include a number, too. For example, a rate of `100 / 30 seconds` will mean "limit requests to a maximum of 100 per every 30 seconds". You can also set the throttling policy on a per-view or per-viewset basis, using the `APIView` class-based views. diff --git a/rest_framework/throttling.py b/rest_framework/throttling.py index c0100f4fb..f1ab0e772 100644 --- a/rest_framework/throttling.py +++ b/rest_framework/throttling.py @@ -106,7 +106,8 @@ class SimpleRateThrottle(BaseThrottle): try: num, period = rate.split('/') num_requests = int(num) - period_timescale = re.findall(r'^\d*[s|m|h|d]', period)[0] + period_timescale = re.findall(r'^\d*[s|m|h|d]', + ''.join(period.split()))[0] period_char = period_timescale[-1] except (ValueError, IndexError): msg = "Incorrect throttle rate set for '%s' scope" % self.scope diff --git a/tests/test_throttling.py b/tests/test_throttling.py index cf1d5635b..00c355010 100644 --- a/tests/test_throttling.py +++ b/tests/test_throttling.py @@ -503,10 +503,16 @@ class SimpleRateThrottleTests(TestCase): rate = SimpleRateThrottle().parse_rate(rate_str) assert rate == (100, 30) - SimpleRateThrottle.rate = '100/10d' - rate = SimpleRateThrottle().parse_rate('100/10d') + rate_str = '100/10d' + SimpleRateThrottle.rate = rate_str + rate = SimpleRateThrottle().parse_rate(rate_str) assert rate == (100, 10 * 86400) + rate_str = '100 / 36 hours' + SimpleRateThrottle.rate = rate_str + rate = SimpleRateThrottle().parse_rate(rate_str) + assert rate == (100, 36 * 3600) + def test_parse_rate_returns_tuple_with_none_if_rate_not_provided(self): rate = SimpleRateThrottle().parse_rate(None) assert rate == (None, None)