how to count number of requests in last second, minute and hour

后端 未结 10 2061
情歌与酒
情歌与酒 2020-12-07 09:35

There is a hypothetical web server which supports only one very simple API - count of requests received in the last hour, minute and second. This server is very popular in t

10条回答
  •  隐瞒了意图╮
    2020-12-07 10:35

    What about a simple list of timestamps? Each time you're making a request you append the current timestamp to the list. And each time you want to check if you're under the rate limit, you first remove timestamps older than 1 hour to prevent stack overflow (hehe) then you count the number of timestamps in the last second, minute, whatever.

    It could be done easily in Python:

    import time
    
    requestsTimestamps = []
    
    def add_request():
        requestsTimestamps.append(time.time())
    
    def requestsCount(delayInSeconds):
        requestsTimestamps = [t for t in requestsTimestamps if t >= time.time() - 3600]
        return len([t for t in requestsTimestamps if t >= time.time() - delayInSeconds])
    

    I guess this can be optimized but you see the idea.

提交回复
热议问题