简体   繁体   English

为 Django 视图执行设置计时器

[英]Set timer for a Django view execution

I'm struggling trying to prevent a Django view from being executed more than once within an hour period.我正在努力阻止 Django 视图在一小时内执行多次。 In other words, if the function runs at 15:00, all future requests for all users should be ignored until 17:00 when it's allowed to run once more again.换句话说,如果 function 在 15:00 运行,则所有用户的所有未来请求都应被忽略,直到 17:00 允许再次运行。

Tried with a timer, but it does get reset every time the view is called.尝试使用计时器,但每次调用视图时都会重置。 Maybe someone can point me in the right direction?也许有人可以指出我正确的方向? Thanks!!!谢谢!!!

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!")

Ultimately, this is what I did and it seems to work fine.最终,这就是我所做的,它似乎工作正常。 I actually need it to run no more than once a day, hence the conditional below.我实际上需要它每天运行不超过一次,因此有以下条件。

Thanks for all the suggestions!!!感谢所有的建议!!!

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

Your timer is being reset everytime because it is inside a function that is execute everytime when request is being made.您的计时器每次都会被重置,因为它位于每次发出请求时都会执行的 function 内。 You should try to set the timer globally, such as outside your function.您应该尝试全局设置计时器,例如在 function 之外。 ( be aware when your script will re-run, timer will be reset again ). (请注意,当您的脚本重新运行时,计时器将再次重置)。

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")

Edit: Handling first request and then starting timer编辑:处理第一个请求,然后启动计时器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM