Merge pull request #537 from pierotofy/hourly

Add hourly req limit option
This commit is contained in:
Piero Toffanin 2023-11-10 15:00:49 -05:00 committed by GitHub
commit 57c7f63cce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 4 deletions

View file

@ -103,7 +103,7 @@ def get_req_limits(default_limit, api_keys_db, multiplier=1):
return req_limit
def get_routes_limits(default_req_limit, daily_req_limit, api_keys_db):
def get_routes_limits(default_req_limit, hourly_req_limit, daily_req_limit, api_keys_db):
if default_req_limit == -1:
# TODO: better way?
default_req_limit = 9999999999999
@ -111,11 +111,17 @@ def get_routes_limits(default_req_limit, daily_req_limit, api_keys_db):
def minute_limits():
return "%s per minute" % get_req_limits(default_req_limit, api_keys_db)
def hourly_limits():
return "%s per hour" % get_req_limits(hourly_req_limit, api_keys_db, int(os.environ.get("LT_HOURLY_REQ_LIMIT_MULTIPLIER", 60)))
def daily_limits():
return "%s per day" % get_req_limits(daily_req_limit, api_keys_db, 1440)
return "%s per day" % get_req_limits(daily_req_limit, api_keys_db, int(os.environ.get("LT_DAILY_REQ_LIMIT_MULTIPLIER", 1440)))
res = [minute_limits]
if hourly_req_limit > 0:
res.append(hourly_limits)
if daily_req_limit > 0:
res.append(daily_limits)
@ -186,7 +192,7 @@ def create_app(args):
api_keys_db = None
if args.req_limit > 0 or args.api_keys or args.daily_req_limit > 0:
if args.req_limit > 0 or args.api_keys or args.daily_req_limit > 0 or args.hourly_req_limit > 0:
api_keys_db = None
if args.api_keys:
api_keys_db = RemoteDatabase(args.api_keys_remote) if args.api_keys_remote else Database(args.api_keys_db_path)
@ -196,7 +202,7 @@ def create_app(args):
limiter = Limiter(
key_func=get_remote_address,
default_limits=get_routes_limits(
args.req_limit, args.daily_req_limit, api_keys_db
args.req_limit, args.hourly_req_limit, args.daily_req_limit, api_keys_db
),
storage_uri=args.req_limit_storage,
)

View file

@ -61,6 +61,11 @@ _default_options_objects = [
'default_value': 'memory://',
'value_type': 'str'
},
{
'name': 'HOURLY_REQ_LIMIT',
'default_value': -1,
'value_type': 'int'
},
{
'name': 'DAILY_REQ_LIMIT',
'default_value': -1,

View file

@ -35,6 +35,13 @@ def get_args():
metavar="<Storage URI>",
help="Storage URI to use for request limit data storage. See https://flask-limiter.readthedocs.io/en/stable/configuration.html. (%(default)s)",
)
parser.add_argument(
"--hourly-req-limit",
default=DEFARGS['HOURLY_REQ_LIMIT'],
type=int,
metavar="<number>",
help="Set the default maximum number of requests per hour per client, in addition to req-limit. (%(default)s)",
)
parser.add_argument(
"--daily-req-limit",
default=DEFARGS['DAILY_REQ_LIMIT'],