Examples
async_lock
/ lock
from py_cachify.asyncio import async_lock
from py_cachify.sync import lock
# Use it within an asynchronous context
async with async_lock('resource_key'):
# Your critical section here
print('Critical section code')
# Use it within a synchronous context
with lock('resource_key'):
# Your critical section here
print('Critical section code')
once
decorator
from datetime import date
from time import sleep
from py_cachify import once
from .celery import celery
@once(key='long_running_function')
async def long_running_function() -> str:
# Executing long-running operation...
pass
@celery.task
@once(key='create-transactions-{for_date.year}-{for_date.month}-{for_date.day}')
def create_transactions(for_date: date) -> None:
# Creating...
pass
@once(key='another_long_running_task', return_on_locked='In progress')
def another_long_running_function() -> str:
sleep(10)
return 'Completed'
@once(key='exception_if_more_than_one_is_running', raise_on_locked=True)
def one_more_long_running_function() -> None:
# Executing
pass
cached
decorator
from py_cachify import cached
@cached(key='example_key', ttl=60)
def expensive_function(x):
print('Executing expensive operation...')
return x ** 2
@cached(key='example_async_function-{arg_a}-{arg_b}')
def async_expensive_function(arg_a: int, arg_b: int) -> int:
return arg_a + arg_b