Debian Codegraph @

examples/optimistic_lock.py

raw
1 import asyncio
2 import logging
3 import random
4
5 from aiocache import Cache
6 from aiocache.lock import OptimisticLock, OptimisticLockError
7
8
9 logger = logging.getLogger(__name__)
10 cache = Cache(Cache.REDIS, endpoint='127.0.0.1', port=6379, namespace='main')
11
12
13 async def expensive_function():
14 logger.warning('Expensive is being executed...')
15 await asyncio.sleep(random.uniform(0, 2))
16 return 'result'
17
18
19 async def my_view():
20
21 async with OptimisticLock(cache, 'key') as lock:
22 result = await expensive_function()
23 try:
24 await lock.cas(result)
25 except OptimisticLockError:
26 logger.warning(
27 'I failed setting the value because it is different since the lock started!')
28 return result
29
30
31 async def concurrent():
32 await cache.set('key', 'initial_value')
33 # All three calls will read 'initial_value' as the value to check and only
34 # the first one finishing will succeed because the others, when trying to set
35 # the value, will see that the value is not the same as when the lock started
36 await asyncio.gather(my_view(), my_view(), my_view())
37
38
39 async def test_redis():
40 await concurrent()
41 await cache.delete("key")
42 await cache.close()
43
44
45 if __name__ == '__main__':
46 asyncio.run(test_redis())