#32023: request.headers doesn't get updated when request.META is updated -----------------------------------------+------------------------ Reporter: lieryan | Owner: nobody Type: New feature | Status: new Component: HTTP handling | Version: 3.1 Severity: Normal | Keywords: Triage Stage: Unreviewed | Has patch: 0 Needs documentation: 0 | Needs tests: 0 Patch needs improvement: 0 | Easy pickings: 0 UI/UX: 0 | -----------------------------------------+------------------------ Currently, Django docs recommended using `request.headers` instead of META to access headers, however the behaviour of `request.headers` currently makes it hard to use correctly during tests.
Currently, the following code fails: {{{ request.META["HTTP_USER_AGENT"] = "foobar" assert request.headers["User-Agent"] == "foobar" # works request.META["HTTP_USER_AGENT"] = "django" assert request.headers["User-Agent"] == "django" # fails }}} This is because `request.headers` is a `@cached_property` that is initialised when request.headers is first accessed, so underlying changes to META don't get reflected to `request.headers`. In regular Django request, this isn't that big of a deal, because arguable `request.META` should be immutable anyway, and you probably should be cursed if you modify `request.META` in production code. However, this is rather annoying when writing tests, because often you want to reuse the same request object to pass to different methods, or you want to test the same method with slightly different header value. Due to this caching, you have the option of either recreating the request from scratch, which can be complicated if parts setting up META is spread between `setUp()` and the test method, or you'd have to delete the `request.headers` to force it to reinitialise, which is rather non obvious and error prone, since you might forget to delete it and cause some tests to pass/fail when they shouldn't. Also, `request.headers` is read only, which means that you still have to use the WSGI environment names when setting headers in tests rather than the standard HTTP name. I'd propose `HttpHeaders` should be reimplemented so that it isn't a real collection, but just an accessor for `request.META`, also that `HttpHeaders` should implement `__getitem__()` which should also update `request.META`. -- Ticket URL: <https://code.djangoproject.com/ticket/32023> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/050.f5aae35dcb8952314dca158855fc76ff%40djangoproject.com.