我正在构建一个允许用户更新网页的应用程序,但我想限制任何用户每 20-30 分钟更新一次。我是否可以简单地将此逻辑添加到视图定义中?
@login_required
def update_options(request):
...
# logic to determine how much time passed since the user visited
...
return render(request, 'main/update-options.html')
我会做这样的事情。我没有测试它,但它应该很接近。基本上使用request.session来跟踪上次更新。
from datetime import datetime
def update_options(request):
if request.session['last_access'] is None or (datetime.now() - request.session['last_access']).days * 24 * 60 > 30:
'YOUR CODE HERE'
request.session['last_access'] = datetime.now()
else:
'TOO MANY TRIES'
return render(request, 'main/update-options.html')
我想出了一个非常简单的方法,尽管建议的答案似乎是另一种合理的方法。我在模型中添加了一个字段,该字段将在用户发布更新后的 10 分钟内保存一个值。然后,我可以引用该字段并检查当前时间是否大于(更晚(用户上次更新后的 10 分钟。
models.py
class Update(models.Model):
update = models.IntegerField(null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
date = models.DateTimeField(auto_now=True) # datetime of object creation
next_allowed_update = models.DateTimeField(
default=datetime.now()+timedelta(minutes=10)-timedelta(hours=5) # adjust for UTC
)
location = models.CharField(max_length=30, default='none')
views.py
@login_required
def update_options(request):
# user can only update once every 10 minutes : 10 set in model
user_latest_update = Update.objects.filter(user=request.user).latest('id')
current_time = datetime.now().replace(tzinfo=None)
next_allowed_update = user_latest_update.next_allowed_update.replace(tzinfo=None)
remaining = str(next_allowed_update - current_time).split(':')
minutes_remaining = int(remaining[1].lstrip("0")) + 1
if current_time > next_allowed_update:
return render(request, 'main/update-options.html')
else:
return render(request, 'main/update-denied.html', {'time_remaining': minutes_remaining})
模板
{% extends "main/base.html" %}
{% block content %}
<div class="container">
<h1>You can update again in {{ time_remaining }} minute</h1>
</div>
{% endblock content %}
此解决方案还允许我呈现视图并传入一个值,以显示用户进行另一次更新之前的分钟数