Add rate limiting functionality to Flask app
- Introduced MemoryRateLimiter for managing request limits. - Added configuration options for enabling rate limiting and setting request limits and time windows. - Implemented methods to enforce rate limits and build rate limit keys based on request context. - Integrated rate limiting checks into the request handling process.
This commit is contained in:
parent
2579ce9f18
commit
20fd9130b7
3 changed files with 153 additions and 0 deletions
37
tests/test_rate_limit.py
Normal file
37
tests/test_rate_limit.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import flask
|
||||
|
||||
|
||||
def test_rate_limit_disabled_by_default():
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return "ok"
|
||||
|
||||
client = app.test_client()
|
||||
|
||||
for _ in range(3):
|
||||
rv = client.get("/")
|
||||
assert rv.status_code == 200
|
||||
|
||||
|
||||
def test_rate_limit_blocks_after_threshold():
|
||||
app = flask.Flask(__name__)
|
||||
app.config.update(
|
||||
RATELIMIT_ENABLED=True,
|
||||
RATELIMIT_REQUESTS=2,
|
||||
RATELIMIT_WINDOW=60,
|
||||
)
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return "ok"
|
||||
|
||||
client = app.test_client()
|
||||
|
||||
assert client.get("/").status_code == 200
|
||||
assert client.get("/").status_code == 200
|
||||
|
||||
rv = client.get("/")
|
||||
assert rv.status_code == 429
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue