在24小时内限制用户操作,并在经过一段时间后重置计数器



我想创建一个函数,从检查给定时区的时间开始,并限制一个人在24小时内可以执行的操作次数。请注意,该功能必须不断检查时间-每次有人与它交互时,它都应该在24小时后将计数器重置为0

我创建了一个"黑客"解决方案,检查时间是否在凌晨1点到23点之间,然后在每次执行操作时在计数器上加1。然后我添加了一个if语句来检查计数器是否超过5,如果发生这种情况,我会打印出一条消息。

然而,我担心这是最有效的方法。

这是我的代码

current_day = datetime.now(pytz.timezone('Africa/Harare'))if (0 <= time.hour) and (1 <= time.minute)
counter = 0 
while (1 <= current_day.hour <= 23):
action
counter +=1
if counter > 5:
print('You have to wait until 1 in the morning tomorrow to get another 5 tries')
break

下面的方法将更优雅,因为它将计算从第一个动作开始的时间,而不是一天开始的时间。

sessionStorage = {} # stores information about user session (time of first action and action counter)
# adds user to session storage with current time and set action counter to 0 
def add_user(user):
sessionStorage[user] = {}
sessionStorage[user][time] = datetime.datetime.now()
sessionStorage[user][counter] = 0
# checks if user can perform action and update action time if needed
def can_perform_action(user)
difference = sessionStorage[user][time] - datetime.datetime.now()
if difference.hours > 24: # check if there lasts 24 hours after first action
# if so, reset action counter and set last action time to current ime
sessionStorage[user][counter] = 0
sessionStorage[user][time] = datetime.datetime.now()
# if action counter is more than 5, then do not allow action
if sessionStorage[user][counter] > 5:
return False
# in all other cases allow action
return True
# increment action counter for current user
def increment_action_counter(user):
sessionStorage[user][counter] += 1

def main():
add_user(user) # create new user
if can_perform_action(user): # check if this user can perform action
# perform action and ...
increment_action_counter(user) # increment action counter

最新更新