Skip to content

Commit

Permalink
Implement rate limiting with Flask-Limiter and add error handling for…
Browse files Browse the repository at this point in the history
… rate limit exceeded
  • Loading branch information
Vianpyro committed Nov 26, 2024
1 parent 9b6bf10 commit b7f9ce6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
17 changes: 16 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@
from flask import Flask, jsonify, redirect
from flask_cors import CORS

from config import Config
from config import Config, limiter
from routes import register_routes

app = Flask(__name__)
app.config.from_object(Config)
CORS(app)
limiter.init_app(app)


@app.route("/", methods=["GET"])
Expand Down Expand Up @@ -51,5 +52,19 @@ def add_common_headers(response):
return response


@app.errorhandler(429)
def ratelimit_error(e):
return (
jsonify(
{
"error": "Too many requests",
"message": "Rate limit exceeded. Please try again later.",
"rate_limit": e.description,
}
),
429,
)


if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
9 changes: 8 additions & 1 deletion config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import os

from dotenv import load_dotenv

from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

# Load environment variables from .env file
load_dotenv()
Expand All @@ -13,3 +14,9 @@ class Config:
MYSQL_PASSWORD = os.getenv("DB_PASSWORD", "myrootpassword")
MYSQL_DB = os.getenv("DB_NAME", "0ce")
MYSQL_CURSORCLASS = "DictCursor"


limiter = Limiter(
key_func=get_remote_address,
default_limits=["1000 per day", "200 per hour", "30 per minute", "3 per second"],
)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
argon2-cffi>=23.1.0
flask>=3.0.3
flask-cors>=5.0.0
Flask-Limiter>=3.8.0
pyjwt>=2.10.0
pymysql>=1.1.1
pytest>=8.3.3
Expand Down

0 comments on commit b7f9ce6

Please sign in to comment.