-
Notifications
You must be signed in to change notification settings - Fork 290
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix a race condition which allowed duplicate consultations to be created
- Loading branch information
Showing
3 changed files
with
154 additions
and
115 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from django.core.cache import cache | ||
from rest_framework.exceptions import APIException | ||
|
||
|
||
class ObjectLocked(APIException): | ||
status_code = 423 | ||
default_detail = "The resource you are trying to access is locked" | ||
default_code = "object_locked" | ||
|
||
|
||
class Lock: | ||
def __init__(self, key, timeout=None): | ||
self.key = f"lock:{key}" | ||
self.timeout = timeout | ||
|
||
def acquire(self): | ||
try: | ||
if not cache.set(self.key, True, self.timeout, nx=True): | ||
raise ObjectLocked() | ||
# handle nx not supported | ||
except TypeError: | ||
if cache.get(self.key): | ||
raise ObjectLocked() | ||
cache.set(self.key, True, self.timeout) | ||
|
||
def release(self): | ||
return cache.delete(self.key) | ||
|
||
def __enter__(self): | ||
self.acquire() | ||
return self | ||
|
||
def __exit__(self, exc_type, exc_value, traceback): | ||
self.release() | ||
return False |