Coverage for ivatar/middleware.py: 89%
19 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-18 23:12 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-18 23:12 +0000
1# -*- coding: utf-8 -*-
2"""
3Middleware classes
4"""
6from django.utils.deprecation import MiddlewareMixin
7from django.middleware.locale import LocaleMiddleware
10class CustomLocaleMiddleware(LocaleMiddleware):
11 """
12 Middleware that extends LocaleMiddleware to skip Vary header processing for image URLs
13 """
15 def process_response(self, request, response):
16 # Check if this is an image-related URL
17 path = request.path
18 if any(
19 path.startswith(prefix)
20 for prefix in ["/avatar/", "/gravatarproxy/", "/blueskyproxy/"]
21 ):
22 # Delete Vary from header if exists
23 if "Vary" in response:
24 del response["Vary"]
26 # Extract hash from URL path for ETag
27 # URLs are like /avatar/{hash}, /gravatarproxy/{hash}, /blueskyproxy/{hash}
28 path_parts = path.strip("/").split("/")
29 if len(path_parts) >= 2:
30 hash_value = path_parts[1] # Get the hash part
31 response["Etag"] = f'"{hash_value}"'
32 else:
33 # Fallback to content hash if we can't extract from URL
34 response["Etag"] = f'"{hash(response.content)}"'
36 # Skip the parent's process_response to avoid adding Accept-Language to Vary
37 return response
39 # For all other URLs, use the parent's behavior
40 return super().process_response(request, response)
43class MultipleProxyMiddleware(
44 MiddlewareMixin
45): # pylint: disable=too-few-public-methods
46 """
47 Middleware to rewrite proxy headers for deployments
48 with multiple proxies
49 """
51 def process_request(self, request): # pylint: disable=no-self-use
52 """
53 Rewrites the proxy headers so that forwarded server is
54 used if available.
55 """
56 if "HTTP_X_FORWARDED_SERVER" in request.META:
57 request.META["HTTP_X_FORWARDED_HOST"] = request.META[
58 "HTTP_X_FORWARDED_SERVER"
59 ]