Skip to content

Commit

Permalink
fix per_session caching (#6169)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcSkovMadsen authored Jan 12, 2024
1 parent d29f5eb commit 86ca4df
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
10 changes: 7 additions & 3 deletions panel/io/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,8 @@ def cache(
max_items=max_items,
ttl=ttl,
to_disk=to_disk,
cache_path=cache_path
cache_path=cache_path,
per_session=per_session,
)
func_hash = None # noqa

Expand Down Expand Up @@ -434,7 +435,7 @@ def wrapped_func(*args, **kwargs):
func_cache[hash_value] = (ret, time, 0, time)
return ret

def clear(session_context=None):
def clear():
global func_hash
# clear called before anything is cached.
if 'func_hash' not in globals():
Expand All @@ -448,10 +449,13 @@ def clear(session_context=None):
else:
cache = state._memoize_cache.get(func_hash, {})
cache.clear()

wrapped_func.clear = clear

if per_session and state.curdoc and state.curdoc.session_context:
state.curdoc.on_session_destroyed(clear)
def server_clear(session_context):
clear()
state.curdoc.on_session_destroyed(server_clear)

try:
wrapped_func.__dict__.update(func.__dict__)
Expand Down
26 changes: 25 additions & 1 deletion panel/tests/io/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
import pathlib
import time

from collections import Counter

import numpy as np
import pandas as pd
import param
import pytest
import requests

try:
import diskcache
Expand All @@ -15,7 +18,8 @@
diskcache_available = pytest.mark.skipif(diskcache is None, reason="requires diskcache")

from panel.io.cache import _find_hash_func, cache
from panel.io.state import set_curdoc
from panel.io.state import set_curdoc, state
from panel.tests.util import serve_and_wait

################
# Test hashing #
Expand Down Expand Up @@ -219,6 +223,26 @@ def test_per_session_cache(document):
assert fn(a=0, b=0) == 0
assert fn(a=0, b=0) == 1

def test_per_session_cache_server(port):
counts = Counter()

@cache(per_session=True)
def get_data():
counts[state.curdoc] += 1
return "Some data"

def app():
get_data()
get_data()
return

serve_and_wait(app, port=port)

requests.get(f"http://localhost:{port}/")
requests.get(f"http://localhost:{port}/")

assert list(counts.values()) == [1, 1]

@pytest.mark.xdist_group("cache")
@diskcache_available
def test_disk_cache():
Expand Down

0 comments on commit 86ca4df

Please sign in to comment.