Consider a function that requires some heavy lifting to be done asynchronously. Calling clients can either recive a cached version immediately, or recive a response that the numbers are being crunched (a valid response for the clients).
Is the following snippet a sound implementation for this pattern?
from django.core import cache
from proj.celery import app
class SomeModel(models.Model):
# ...
def get_crunched_numbers(self):
cache_key = 'foo:{}'.format(self.id)
res = cache.get(cache_key)
if not res:
@app.task
def gen_crunched_numbers():
res = do_heavy_lifting()
cache.set(cache_key, res)
return res
gen_crunched_numbers.delay()
return 'crunching... come back later'
else:
return res
Are there better alternatives to running Celery tasks like so, while containing all the logic in a single piece of code?
Edit: as mentioned in the comments, this code doesn't even work. So any suggestions on a nice pattern are much obliged.