我正在努力防止Django视图在一小时内被执行多次。换言之,如果函数在15:00运行,则所有用户的所有未来请求都应被忽略,直到17:00才允许再次运行。
尝试使用计时器,但每次调用视图时都会重置。也许有人能给我指明正确的方向?谢谢
import threading as th
def hello():
print("hello, world")
def webhook(request):
tm = th.Timer(3600, hello)
if request.method == 'POST' and not tm.is_alive():
tm.start()
code_to.ecexute()
return HttpResponse("Webhook received!")
最终,这就是我所做的,而且似乎工作得很好。事实上,我需要它每天运行不超过一次,因此有以下条件。
感谢所有的建议!!!
def webhook2 (request):
today = datetime.now().date()
with open('timestamp.txt') as f:
tstamp = f.read()
last_run = datetime.strptime(tstamp, '%Y-%m-%d')
last_run_date = datetime.date(last_run)
print ("last run: " + str(last_run_date))
if last_run_date < today:
file = open("timestamp.txt" ,"w")
file.write(str(today))
file.close()
if request.method == 'POST':
msg = str(request.body)
final_msg=msg[2:-1]
print("Data received from Webhook is: ", request.body)
# creates a google calendar event
function_logic()
return HttpResponse("Webhook received! Event added to calendar")
else:
print ("we already have a record for today")
return HttpResponse("Not adding a record. We already have one for today.")
您的计时器每次都会被重置,因为它在每次发出请求时都会执行的函数中。您应该尝试全局设置计时器,例如在您的功能之外。(注意脚本何时重新运行,计时器将再次重置(。
import threading as th
def hello():
print("hello, world")
tm = None
def webhook(request):
# check here if timer is dead then process the request.
if timer_is_dead || tm is None:
# accessing global value and setting it for first time
if tm is None:
global tm
tm = th.Timer(3600, hello)
tm.start()
if request.method == 'POST' and not tm.is_alive():
code_to.ecexute()
# start timer again for next hour
return HttpResponse("Webhook received!")
else:
return HttResponse("Not Allowed")
编辑:处理第一个请求,然后启动计时器