Skip to content

Commit 97fcda7

Browse files
committed
Switch to Store.request_ids and remove serialization force_str.
If the serialization logic begins throwing exceptions we can consider subclassing the encoder class and using force_str on the object itself.
1 parent 19b5695 commit 97fcda7

File tree

2 files changed

+27
-46
lines changed

2 files changed

+27
-46
lines changed

debug_toolbar/store.py

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,19 @@
1+
import contextlib
12
import json
23
from collections import defaultdict, deque
34
from typing import Any, Dict, Iterable
45

56
from django.core.serializers.json import DjangoJSONEncoder
6-
from django.utils.encoding import force_str
77
from django.utils.module_loading import import_string
88

99
from debug_toolbar import settings as dt_settings
1010

1111

12-
class DebugToolbarJSONEncoder(DjangoJSONEncoder):
13-
def default(self, o: Any) -> Any:
14-
try:
15-
return super().default(o)
16-
except TypeError:
17-
return force_str(o)
18-
19-
2012
def serialize(data: Any) -> str:
21-
return json.dumps(data, cls=DebugToolbarJSONEncoder)
13+
# If this starts throwing an exceptions, consider
14+
# Subclassing DjangoJSONEncoder and using force_str to
15+
# make it JSON serializable.
16+
return json.dumps(data, cls=DjangoJSONEncoder)
2217

2318

2419
def deserialize(data: str) -> Any:
@@ -29,8 +24,8 @@ class BaseStore:
2924
_config = dt_settings.get_config().copy()
3025

3126
@classmethod
32-
def ids(cls) -> Iterable:
33-
"""The stored ids"""
27+
def request_ids(cls) -> Iterable:
28+
"""The stored request ids"""
3429
raise NotImplementedError
3530

3631
@classmethod
@@ -68,43 +63,41 @@ class MemoryStore(BaseStore):
6863
# ids is the collection of storage ids that have been used.
6964
# Use a dequeue to support O(1) appends and pops
7065
# from either direction.
71-
_ids: deque = deque()
66+
_request_ids: deque = deque()
7267
_request_store: Dict[str, Dict] = defaultdict(dict)
7368

7469
@classmethod
75-
def ids(cls) -> Iterable:
76-
"""The stored ids"""
77-
return cls._ids
70+
def request_ids(cls) -> Iterable:
71+
"""The stored request ids"""
72+
return cls._request_ids
7873

7974
@classmethod
8075
def exists(cls, request_id: str) -> bool:
8176
"""Does the given request_id exist in the request store"""
82-
return request_id in cls._ids
77+
return request_id in cls._request_ids
8378

8479
@classmethod
8580
def set(cls, request_id: str):
8681
"""Set a request_id in the request store"""
87-
if request_id not in cls._ids:
88-
cls._ids.append(request_id)
89-
for _ in range(len(cls._ids) - cls._config["RESULTS_CACHE_SIZE"]):
90-
removed_id = cls._ids.popleft()
82+
if request_id not in cls._request_ids:
83+
cls._request_ids.append(request_id)
84+
for _ in range(len(cls._request_ids) - cls._config["RESULTS_CACHE_SIZE"]):
85+
removed_id = cls._request_ids.popleft()
9186
cls._request_store.pop(removed_id, None)
9287

9388
@classmethod
9489
def clear(cls):
9590
"""Remove all requests from the request store"""
96-
cls._ids.clear()
91+
cls._request_ids.clear()
9792
cls._request_store.clear()
9893

9994
@classmethod
10095
def delete(cls, request_id: str):
10196
"""Delete the stored request for the given request_id"""
10297
cls._request_store.pop(request_id, None)
103-
try:
104-
cls._ids.remove(request_id)
105-
except ValueError:
106-
# The request_id doesn't exist in the collection of ids.
107-
pass
98+
# Suppress when request_id doesn't exist in the collection of ids.
99+
with contextlib.suppress(ValueError):
100+
cls._request_ids.remove(request_id)
108101

109102
@classmethod
110103
def save_panel(cls, request_id: str, panel_id: str, data: Any = None):

tests/test_store.py

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,6 @@ def test_serialize(self):
1111
'{"hello": {"foo": "bar"}}',
1212
)
1313

14-
def test_serialize_force_str(self):
15-
class Foo:
16-
spam = "bar"
17-
18-
def __str__(self):
19-
return f"Foo spam={self.spam}"
20-
21-
self.assertEqual(
22-
store.serialize({"hello": Foo()}),
23-
'{"hello": "Foo spam=bar"}',
24-
)
25-
2614
def test_deserialize(self):
2715
self.assertEqual(
2816
store.deserialize('{"hello": {"foo": "bar"}}'),
@@ -38,7 +26,7 @@ def test_methods_are_not_implemented(self):
3826
]
3927
self.assertEqual(len(methods), 7)
4028
with self.assertRaises(NotImplementedError):
41-
store.BaseStore.ids()
29+
store.BaseStore.request_ids()
4230
with self.assertRaises(NotImplementedError):
4331
store.BaseStore.exists("")
4432
with self.assertRaises(NotImplementedError):
@@ -64,7 +52,7 @@ def tearDown(self) -> None:
6452
def test_ids(self):
6553
self.store.set("foo")
6654
self.store.set("bar")
67-
self.assertEqual(list(self.store.ids()), ["foo", "bar"])
55+
self.assertEqual(list(self.store.request_ids()), ["foo", "bar"])
6856

6957
def test_exists(self):
7058
self.assertFalse(self.store.exists("missing"))
@@ -73,14 +61,14 @@ def test_exists(self):
7361

7462
def test_set(self):
7563
self.store.set("foo")
76-
self.assertEqual(list(self.store.ids()), ["foo"])
64+
self.assertEqual(list(self.store.request_ids()), ["foo"])
7765

7866
def test_set_max_size(self):
7967
existing = self.store._config["RESULTS_CACHE_SIZE"]
8068
self.store._config["RESULTS_CACHE_SIZE"] = 1
8169
self.store.save_panel("foo", "foo.panel", "foo.value")
8270
self.store.save_panel("bar", "bar.panel", {"a": 1})
83-
self.assertEqual(list(self.store.ids()), ["bar"])
71+
self.assertEqual(list(self.store.request_ids()), ["bar"])
8472
self.assertEqual(self.store.panel("foo", "foo.panel"), {})
8573
self.assertEqual(self.store.panel("bar", "bar.panel"), {"a": 1})
8674
# Restore the existing config setting since this config is shared.
@@ -89,20 +77,20 @@ def test_set_max_size(self):
8977
def test_clear(self):
9078
self.store.save_panel("bar", "bar.panel", {"a": 1})
9179
self.store.clear()
92-
self.assertEqual(list(self.store.ids()), [])
80+
self.assertEqual(list(self.store.request_ids()), [])
9381
self.assertEqual(self.store.panel("bar", "bar.panel"), {})
9482

9583
def test_delete(self):
9684
self.store.save_panel("bar", "bar.panel", {"a": 1})
9785
self.store.delete("bar")
98-
self.assertEqual(list(self.store.ids()), [])
86+
self.assertEqual(list(self.store.request_ids()), [])
9987
self.assertEqual(self.store.panel("bar", "bar.panel"), {})
10088
# Make sure it doesn't error
10189
self.store.delete("bar")
10290

10391
def test_save_panel(self):
10492
self.store.save_panel("bar", "bar.panel", {"a": 1})
105-
self.assertEqual(list(self.store.ids()), ["bar"])
93+
self.assertEqual(list(self.store.request_ids()), ["bar"])
10694
self.assertEqual(self.store.panel("bar", "bar.panel"), {"a": 1})
10795

10896
def test_panel(self):

0 commit comments

Comments
 (0)