Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix per_session caching #6169

Merged
merged 2 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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