Reputation: 51
I am new to Django.
My Project (for example) -
project/ # project dir (the one which django-admin.py created)
myapp/ # my app
__init__.py
models.py
views.py
urls.py
...
project/ # settings for the project
__init__.py
settings.py
wsgi.py
...
My app exposes an URL (lets say),
http://127.0.0.1:8000/myapp/
When ever I call the above mentioned URL, this method is invoked in myapp/views.py -
def index(request):
req_data = some_method_which_does_processing()
return render(request, 'myapp/index.html', {'req_data': req_data})
What I want achieve is the following, I don't want "some_method_which_does_processing()" this method to be executed every time when user hits this URL "http://127.0.0.1:8000/myapp/". I want to add a logic wherein this method is called when user hits the above mentioned URL 10 times. I want to know if Django exposes something to cover this specific scenario
Upvotes: 0
Views: 235
Reputation: 3327
user based, single user hit the view ten times, then the function is triggerd
def index(request):
try:
request.session['hit_num'] += 1 # counter
# first time access, reqets.session['hit_num'] does not exists yet
except KeyError:
request.session['hit_num'] = 1
if request.session['hit_num'] == 10:
req_data = some_method_which_does_processing()
del request.session['hit_num'] # remove the hit_num from user session, so next time it will count from 1 again
return render(request, 'myapp/index.html', {'req_data': req_data})
return render(request, 'myapp/index.html', {'req_data': 'N/A'})
request based, request accumulated to ten times, function is triggered
COUNTER = 0
def index(request):
global COUNTER
COUNTER += 1
if COUNTER == 10:
req_data = some_method_which_does_processing()
COUNTER = 0 # from 0 again
return render(request, 'myapp/index.html', {'req_data': req_data})
return render(request, 'myapp/index.html', {'req_data': 'N/A'})
Upvotes: 1