Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add requests rate limit #15

Merged
merged 2 commits into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@
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)

if app.config["TESTING"]:
limiter.enabled = False


@app.route("/", methods=["GET"])
def home():
Expand Down Expand Up @@ -51,5 +54,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