Hello Friends,
I am back :)
First Wish you a very happy new year.
I know it's too late ;)
Today we are going to learn how can we execute a task only one time for some some specific time period .
Example : You want to give bonus to any user only one time in a day when user access 'about-us' template.
So Let user access that page multiple times in a day still user will got bonus will once.
Guess about-us is django view .
<pre>
from functools import wraps
from django.core.cache import cache
def execute_once_in(seconds):
def decorator(func):
def inner_decorator(*args, **kwargs):
key = "%s.%s" % (func.__module__, func.__name__)
#Django used localmemcache as local cache system
key = key.replace(' ','_') # memcache doesn't like spaces
# func() didn't execute or returned nothing
if cache.get(key):
return
cache.set(key, True, seconds)
return func(*args, **kwargs)
return wraps(func)(inner_decorator)
return decorator
@execute_once_in(5) # function will execute only once in each 5 second .
def bonus():
print "we are executing logic for bonus"
def about_us(request):
bonus()
#execution
</pre>
I am back :)
First Wish you a very happy new year.
I know it's too late ;)
Today we are going to learn how can we execute a task only one time for some some specific time period .
Example : You want to give bonus to any user only one time in a day when user access 'about-us' template.
So Let user access that page multiple times in a day still user will got bonus will once.
Guess about-us is django view .
<pre>
from functools import wraps
from django.core.cache import cache
def execute_once_in(seconds):
def decorator(func):
def inner_decorator(*args, **kwargs):
key = "%s.%s" % (func.__module__, func.__name__)
#Django used localmemcache as local cache system
key = key.replace(' ','_') # memcache doesn't like spaces
# func() didn't execute or returned nothing
if cache.get(key):
return
cache.set(key, True, seconds)
return func(*args, **kwargs)
return wraps(func)(inner_decorator)
return decorator
@execute_once_in(5) # function will execute only once in each 5 second .
def bonus():
print "we are executing logic for bonus"
def about_us(request):
bonus()
#execution
</pre>