cachecontrol icon indicating copy to clipboard operation
cachecontrol copied to clipboard

Caching of POST request, but dependent on data/json

Open blueyed opened this issue 6 years ago • 1 comments

I'd like to cache responses for POST requests, but only for matching data / json (similar to params have to match for GET requests).

This however does not appear to be possible easily, is it?

Related code: https://github.com/ionrock/cachecontrol/blob/7a198b41a14ac92cf3766599009326165dcc99cd/cachecontrol/controller.py#L125-L148

  • you cannot "encode" it in the request_url, since that only gets request.url (and would be too long anyway etc)
  • the cache lookup also gets the "cache_url" only (not the whole request)
  • the serializer then could return False, but it would mean that there's a misleading log warning, and that only the latest (matching) response would be cached

blueyed avatar Dec 06 '19 14:12 blueyed

Note that requests-cache uses the request.body with the cache key: https://github.com/reclosedev/requests-cache/blob/master/requests_cache/backends/base.py#L218-L233

blueyed avatar Dec 27 '19 09:12 blueyed

Sorry for the extremely belated response here.

This is indeed not possible, for reasons mentioned in both #216 and #337. The TL;DR is that CacheControl is not architecturally set up to cache POSTs, but also that the HTTP RFCs explicitly preclude caching of state-modifying methods like POST.

If you're working in a particular application context where POST caching makes sense, my recommendation is to either do it via your own custom middleware, or handle it at a higher layer (i.e. write an adapter above your session management to divert POSTs that have been cached).

woodruffw avatar Jul 03 '24 21:07 woodruffw