Coverage for website/thaliawebsite/api/throttling.py: 38.89%

14 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2025-08-14 10:31 +0000

1from rest_framework.throttling import SimpleRateThrottle 

2 

3 

4class AnonRateThrottle(SimpleRateThrottle): 

5 """Limits the rate of API calls that may be made by a anonymous users. 

6 

7 The IP address of the request will be used as the unique cache key. 

8 """ 

9 

10 scope = "anon" 

11 

12 def get_cache_key(self, request, view): 

13 if request.user and request.user.is_authenticated: 

14 return None # Only throttle unauthenticated requests. 

15 

16 return self.cache_format % { 

17 "scope": self.scope, 

18 "ident": self.get_ident(request), 

19 } 

20 

21 

22class UserRateThrottle(SimpleRateThrottle): 

23 """Limits the rate of API calls that may be made by a given user. 

24 

25 The user id will be used as a unique cache key if the user is 

26 authenticated. For anonymous requests, the IP address of the request will 

27 be used. 

28 """ 

29 

30 scope = "user" 

31 

32 def get_cache_key(self, request, view): 

33 if request.user and request.user.is_authenticated: 

34 ident = request.user.pk 

35 else: 

36 ident = self.get_ident(request) 

37 

38 return self.cache_format % {"scope": self.scope, "ident": ident}