The problem is that you maintain just one set of call counts. But that means each Flask request shares call counts with all the other requests. What you need to do is to maintain a separate set of call counts for each Flask request.
From reading the API documentation it looks as though the way to make this work is to carry out these three steps:
Make a subclass of
flask.Request
that can store your function call counts:import collections import flask class MyRequest(flask.Request): """A subclass of Request that maintains function call counts.""" def __init__(self, *args, **kwargs): super(MyRequest, self).__init__(*args, **kwargs) self.call_counts = collections.defaultdict(int)
Set
request_class
to your subclass when you initialize your application:app = flask.Flask(__name__, request_class=MyRequest, ...)
Rewrite your decorator to store its counts in the global
flask.request
object:import functools def max_calls(num, default=None): """Decorator which allows its wrapped function to be called at most `num` times per Flask request, but which then returns `default`. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if flask.request.call_counts[func] == num: return default flask.request.call_counts[func] += 1 return func(*args, **kwargs) return wrapper return decorator
But having written that, it would be remiss for me not to point out that your question seems very strange. Why do you want to restrict the number of times a function can be called by a Flask request? Are you trying to do some kind of rate limiting? It seems likely that whatever you want to do can be done better using some other approach.