Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Limiter error: TypeError: Limiter.__init__() got multiple values for argument 'key_func'

I am attempting to use Flask's rate limiting library to rate limit an API based on the seconds.

So I have used this exact same format to limit requests to an API on an Apache Server. However I am now using an NGINX. I do not thinks this makes a difference but when I run this code:

import api

app = Flask(__name__, instance_relative_config=True)

limiter = Limiter(app, default_limits=["5/second"], key_func=lambda: get_remote_address)

limiter.limit("5/second", key_func=lambda: request.args.get('token') if 'token' in request.args else get_remote_address)(api.bp)

app.register_blueprint(api.bp)

Again I have ran this exact same code on another server, but now it is giving this error:

limiter = Limiter(app, "5/second", key_func=lambda:
request.args.get('token') if 'token' in request.args else get_remote_address)

TypeError: Limiter.__init__() got multiple values for argument 'key_func'

Any help would be great. I am using Flask-Limiter in python and running gevent on gunicorn server for NGINX.

like image 738
Justin Battaglia Avatar asked Jan 25 '26 14:01

Justin Battaglia


2 Answers

Your Limiter class instantiation is incorrect. Below is the correct one-

limiter = Limiter(get_remote_address, app=app, default_limits=["200 per day", "50 per hour"])

like image 157
Amit Dwivedi Avatar answered Jan 27 '26 06:01

Amit Dwivedi


In your original code, since app is also a parameter of the init() function, app will be interpreted as the value of key_func, and then you pass the value of the second key_func parameter through key_func=get_remote_address, resulting in init() The function received more than one value for the key_func parameter, thus throwing an error.

The following is the definition of limiter:

 def __init__(
    self,
    key_func: Callable[[], str],
    *,
    app: Optional[flask.Flask] = None,
    default_limits: Optional[List[Union[str, Callable[[], str]]]] = None,
    default_limits_per_method: Optional[bool] = None,
    default_limits_exempt_when: Optional[Callable[[], bool]] = None,
    default_limits_deduct_when: Optional[...
like image 20
frankha Avatar answered Jan 27 '26 05:01

frankha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!