Open mjpieters opened 1 year ago
One caveat: currently you can't use Annotated
on BackgroundTasks
or any of the other non-field parameters. I've requested that FastAPI fix this.
I can't, currently, see any use case where a non-field parameter should be part of the cache key, so I'm going to treat those as IgnoreArg
by default and document this.
The context
Currently, if your cached endpoint uses arguments that should be ignored when generating a cache key, you have no choice but to create a custom key builder.
E.g. the following endpoint will almost never return a cached response, because the
background_tasks
dependency will rarely produce the same cache key value (example based on the FastAPI documentation):You'd have to write a custom key builder here; you could still delegate to the default keybuilder after removing certain arguments:
The above key builder is generic enough that it can be used as the key builder for the whole project at least.
Annotated arguments
But, what if you could simply annotate arguments that should not be part of the key?
It could look something like this:
IgnoredArg
is just a sentinel object here:The cache decorator could trivially filter out such arguments by introspecting the endpoint signature:
and the
ignored
set can then be used to remove names from thekwargs
dictionary before passing it to the key builder.Annotations to convert argument values to key components
You could take this concept another step further, and use such annotations to register argument converters to produce key components. Another example:
The cache decorator would then pass the
email
argument through thecanonical_email()
callable before passing on the arguments to the key builder.