你可以用成对的
(command, ip)
作为你的日志字典的钥匙。
另外,我推荐最好的
dictionary method
dict.setdefault
.
exec_logs = {}
threshold_per_hour = 3
def exec_command(command_name, ip, current_hour):
previous_hour, n = exec_logs.setdefault((command_name, ip), (current_hour, 0))
if previous_hour == current_hour:
if n >= threshold_per_hour:
print('Command aborted: User {} cannot execute command {} more than {} times per hour.'.format(ip, command_name, threshold_per_hour))
return # do not execute command
else:
exec_logs[(command_name, ip)] = (current_hour, n+1)
print('Command {} successfully executed.'.format(command_name))
else:
exec_logs[(command_name, ip)] = (current_hour, 1)
print('Command {} successfully executed.'.format(command_name))
测试:
>>> exec_command('make coffee', 127, '1pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 127, '1pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 127, '1pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 127, '1pm')
Command aborted: User 127 cannot execute command make coffee more than 3 times per hour.
>>> exec_logs
{('make coffee', 127): ('1pm', 3)}
>>> exec_command('make coffee', 127, '2pm')
Command make coffee successfully executed.
>>> exec_logs
{('make coffee', 127): ('2pm', 1)}
>>> exec_command('make coffee', 139, '2pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 139, '2pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 139, '2pm')
Command make coffee successfully executed.
>>> exec_logs
{('make coffee', 127): ('2pm', 1), ('make coffee', 139): ('2pm', 3)}