Django:当URL命中10次时,执行与views.py中的URL关联的方法的特定部分的逻辑

Django: Logic to execute certain part of a method associated with a URL in views.py, when URL hits 10 times

我是 Django 新手。

我的项目(举例)-

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
    ...

我的应用公开了一个 URL(比方说),

http://127.0.0.1:8000/myapp/

每当我调用上面提到的 URL 时,都会在 myapp/views.py -

中调用此方法
def index(request):
    req_data = some_method_which_does_processing()
    return render(request, 'myapp/index.html', {'req_data': req_data})

我想要实现的是以下, 我不希望每次用户点击此 URL“http://127.0.0.1:8000/myapp/”时执行“some_method_which_does_processing()”此方法。 我想添加一个逻辑,其中当用户点击上述 URL 10 次时调用此方法。 我想知道 Django 是否公开了一些内容来涵盖这个特定场景

基于用户,单个用户点击视图十次,然后触发该功能

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'})

基于请求,请求累积到10次,触发函数

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'})