Skip to content

Commit

Permalink
Add URLScopedRateThrottle throttle class
Browse files Browse the repository at this point in the history
Co-Authored-By: Kelvin Muchiri <kelvinmuchiri63@gmail.com>
  • Loading branch information
FrankApiyo and kelvin-muchiri committed Aug 29, 2024
1 parent 24a5208 commit 7bb2e6e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
23 changes: 22 additions & 1 deletion onadata/libs/tests/test_throttle.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,30 @@
from django.core.cache import cache
from django.contrib.auth.models import AnonymousUser
from django.test import TestCase, override_settings

from rest_framework.test import APIRequestFactory

from onadata.libs.throttle import RequestHeaderThrottle
from onadata.libs.throttle import RequestHeaderThrottle, URLScopedRateThrottle

class URLScopedThrottlingTests(TestCase):


def setUp(self):
"""
Reset the cache so that no throttles will be active
"""
cache.clear()
self.factory = APIRequestFactory()
self.throttle = URLScopedRateThrottle()

def test_cache_key_is_correctly_set(self):
"""
Cache key is set correctly by anonymous user
"""
request = self.factory.get("/bob/submission")
request.user = AnonymousUser()
key = self.throttle.get_cache_key(request, None)
self.assertEqual(key,'/bob/submission_throttle_None_127.0.0.1')


class ThrottlingTests(TestCase):
Expand Down
11 changes: 10 additions & 1 deletion onadata/libs/throttle.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@

from django.conf import settings

from rest_framework.throttling import SimpleRateThrottle
from rest_framework.throttling import SimpleRateThrottle, ScopedRateThrottle


class URLScopedRateThrottle(ScopedRateThrottle):

def get_cache_key(self, request, view):
"""
Override ScopedRatheThrottle method
"""
return f'{request.path}_{super().get_cache_key(request, view)}'


class RequestHeaderThrottle(SimpleRateThrottle):
Expand Down

0 comments on commit 7bb2e6e

Please sign in to comment.