首页 > 解决方案 > 在 24 小时内限制用户操作并在时间过去后重置计数器

问题描述

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

我创建了一个“hacky”解决方案,它检查时间是否在凌晨 1 点到 2300 小时之间,然后在每次有人执行操作时向计数器添加 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

标签: python

解决方案


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

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

推荐阅读