-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocks.py
33 lines (25 loc) · 868 Bytes
/
locks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import time
from contextlib import contextmanager
from django.core.cache import cache
LOCK_EXPIRE = 60 * 10 # Lock expires in 10 minutes
@contextmanager
def redis_lock(lock_id, oid):
timeout_at = time.monotonic() + LOCK_EXPIRE - 3
status = cache.add(lock_id, oid, timeout=LOCK_EXPIRE)
try:
yield status
finally:
if time.monotonic() < timeout_at and status:
cache.delete(lock_id)
@contextmanager
def memcached_lock(lock_id, oid):
timeout_at = time.monotonic() + LOCK_EXPIRE - 3
from django.core.cache import caches
from django.utils.connection import ConnectionProxy
cache = ConnectionProxy(caches, 'memcached')
status = cache.add(lock_id, oid, timeout=LOCK_EXPIRE)
try:
yield status
finally:
if time.monotonic() < timeout_at and status:
cache.delete(lock_id)