Skip to content

Commit

Permalink
Catch IntegrityError in bolt cache set and return existing value
Browse files Browse the repository at this point in the history
  • Loading branch information
davegaeddert committed Feb 2, 2024
1 parent 8809012 commit 814760b
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions bolt-cache/bolt/cache/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta
from functools import cached_property

from bolt.db import IntegrityError, transaction
from bolt.utils import timezone


Expand Down Expand Up @@ -62,12 +63,18 @@ def set(self, value, expiration: datetime | timedelta | int | float | None = Non
# Keep existing expires_at value or None
pass

item, _ = self._model_class.objects.update_or_create(
key=self.key, defaults=defaults
)
try:
with transaction.atomic():
item, _ = self._model_class.objects.update_or_create(
key=self.key, defaults=defaults
)
except IntegrityError:
# Most likely a race condition in creating the item
# so we'll effectively do a get and return the stored value
self.reload()
return self.value

self.reload()

return item.value

def delete(self):
Expand Down

0 comments on commit 814760b

Please sign in to comment.