Opened 94 minutes ago
Last modified 79 minutes ago
#37054 assigned Cleanup/optimization
Precompute the Referrer-Policy header value during middleware initialization
| Reported by: | Mason Lyons | Owned by: | Mason Lyons |
|---|---|---|---|
| Component: | HTTP handling | Version: | 6.0 |
| Severity: | Normal | Keywords: | middleware |
| Cc: | Mason Lyons | Triage Stage: | Unreviewed |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
The SecurityMiddleware runs on every Django request and adds security headers to responses. The original process_response() method constructs the Referrer-Policy header by performing string operations on every request:
def process_response(self, request, response):
# ... other headers ...
if self.referrer_policy:
# Support a comma-separated string or iterable of values to allow
# fallback.
response.headers.setdefault(
"Referrer-Policy",
",".join(
[v.strip() for v in self.referrer_policy.split(",")]
if isinstance(self.referrer_policy, str)
else self.referrer_policy
),
)
Move the string manipulation to __init__() where it runs once when the middleware is initialized, storing the pre-computed value for use in process_response()
Note:
See TracTickets
for help on using tickets.
PR available: https://github.com/django/django/pull/21146