Coverage for ivatar/middleware.py: 95%

20 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-11-04 00:07 +0000

1""" 

2Middleware classes 

3""" 

4 

5from django.utils.deprecation import MiddlewareMixin 

6from django.middleware.locale import LocaleMiddleware 

7 

8 

9class CustomLocaleMiddleware(LocaleMiddleware): 

10 """ 

11 Middleware that extends LocaleMiddleware to skip Vary header processing for image URLs 

12 """ 

13 

14 def process_response(self, request, response): 

15 # Check if this is an image-related URL 

16 path = request.path 

17 if any( 

18 path.startswith(prefix) 

19 for prefix in ["/avatar/", "/gravatarproxy/", "/blueskyproxy/"] 

20 ): 

21 # Delete Vary from header if exists 

22 if "Vary" in response: 

23 del response["Vary"] 

24 

25 # Extract hash from URL path for ETag 

26 # URLs are like /avatar/{hash}, /gravatarproxy/{hash}, /blueskyproxy/{hash} 

27 path_parts = path.strip("/").split("/") 

28 if len(path_parts) >= 2: 

29 hash_value = path_parts[1] # Get the hash part 

30 # Sanitize hash_value to remove newlines and other control characters 

31 # that would cause BadHeaderError 

32 hash_value = "".join( 

33 c for c in hash_value if c.isprintable() and c not in "\r\n" 

34 ) 

35 response["Etag"] = f'"{hash_value}"' 

36 else: 

37 # Fallback to content hash if we can't extract from URL 

38 response["Etag"] = f'"{hash(response.content)}"' 

39 

40 # Skip the parent's process_response to avoid adding Accept-Language to Vary 

41 return response 

42 

43 # For all other URLs, use the parent's behavior 

44 return super().process_response(request, response) 

45 

46 

47class MultipleProxyMiddleware( 

48 MiddlewareMixin 

49): # pylint: disable=too-few-public-methods 

50 """ 

51 Middleware to rewrite proxy headers for deployments 

52 with multiple proxies 

53 """ 

54 

55 def process_request(self, request): # pylint: disable=no-self-use 

56 """ 

57 Rewrites the proxy headers so that forwarded server is 

58 used if available. 

59 """ 

60 if "HTTP_X_FORWARDED_SERVER" in request.META: 

61 request.META["HTTP_X_FORWARDED_HOST"] = request.META[ 

62 "HTTP_X_FORWARDED_SERVER" 

63 ]