python - 在 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
解决方案
下面的方法会更优雅,因为它会从第一个动作开始计算时间,而不是一天的开始。
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
推荐阅读
- java - 接口隔离原理如何实现多态性?
- python-3.x - DRF 和 Knox 将登录用户显示为匿名 (Django)
- python - 在 Python 脚本中通过 ssh 调用 Python 会导致“非法指令(核心转储)”
- reactjs - 谁在使用 typescript 和 react saga 的 react JS 中从 API 加载下拉选项?
- json - 将文本解析为对话框如何颤动
- python - Dash DataTable 用 null 或空字符串值替换粘贴到下拉单元格中的错误值
- java - 内部bean会根据问题创建吗?
- c++ - C ++为简单的数学计算提供错误的输出
- java - JavaFx ComboBox 在第一次点击时没有得到正确的值
- sorting - 为什么奇偶排序的时间复杂度是O(n^2)?对于我的 3 个案例