I have a Tornado web server. I wonder if there is anyway I can control the number of incoming requests? I want to only accept x number of requests from a single client in a given timeframe.
Asked
Active
Viewed 90 times
1 Answers
1
Set a cookie with the expiry as the timeframe you want to be and use this cookie to keep count of requests.
code sample:
lets say you want the timeframe to be of one day, so here is how you would set the cookie. Do this when user logged in (or after any action you want):
set_secure_cookie('requestscount', '0', expires_days=1)
and then check the count value before giving access to the resource:
user_requests = int(get_secure_cookie('requestscount'))
if user_requests < MAX_USER_REQUESTS:
user_requests += 1
set_secure_cookie('requestscount', str(user_requests), expires_days=1)
# serve the resource to user
...
Of course there are other ways. You could keep this count in a database instead of a cookie.

avi
- 9,292
- 11
- 47
- 84
-
Good answer but it has a problem. Cookies can be cleared. So if that is not an issue for you, then go ahead. But, otherwise you need the counter to be stored on the server. If your users can be uniquely identified (by a token, username, email, etc.) then maintain the counts on the server. Redis is a good candidate for storage. Although you can store it anywhere depending on your usage. – vaidik Jul 19 '14 at 14:09