sqlalchemy / sqlalchemy/dogpile.cache

Add a post-cache-load hook

Open
#28 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
299
Forks
50
PR merge metrics
No merged PRs in 30d

Description

Migrated issue, originally created by Wichert Akkerman (wichert)

It would be practical if there was a way to detect that data was returned from the cache and then do some extra post-processing. My particular use case is caching SQLAlchemy ORM instances which needs to be merged into the session. Currently I am doing something like this:

:::python
@region.cache_on_arguments()
def _expensive_function(foo, bar):
    ...

def expensive_function(foo, bar):
    result = _expensive_function(foo, bar)
    if result not in session:
        session.merge(result, load=False)
    return result

This could be reworked as a decorator to be more generic and easier to read, but it still has to do this in-session check and possible merge on every invocation instead of only for cache hits. It would be nice to be able to do this:

:::python
def _merge(obj):
    session.merge(obj, load=False)

@region.cache_on_arguments(on_cache_hit=_merge)
def _expensive_function(foo, bar):
    ...

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the Python implementation of cache_on_arguments and tracing how cache hits are handled. Define the callback behavior and verify it with the relevant cache decorator tests; done should mean the hook runs only after cached data is returned without changing normal misses.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sqlalchemy
Domain
api, backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.