add: api for rate control
This commit is contained in:
@@ -100,6 +100,21 @@ def require_auth(roles=[]):
|
|||||||
return wrapper
|
return wrapper
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
|
rate_limits = {}
|
||||||
|
default_rate_limit = "60 per minute"
|
||||||
|
def init_rate_limits(app):
|
||||||
|
global rate_limits
|
||||||
|
rate_limits = {
|
||||||
|
f"{rule.rule} : {method}": default_rate_limit
|
||||||
|
for rule in app.url_map.iter_rules()
|
||||||
|
for method in rule.methods
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_rate_limit():
|
||||||
|
key = f"{request.path} : {request.method}"
|
||||||
|
return rate_limits.get(key, default_rate_limit)
|
||||||
|
|
||||||
|
|
||||||
limiter = Limiter(
|
limiter = Limiter(
|
||||||
key_func=get_remote_address,
|
key_func=get_remote_address,
|
||||||
@@ -118,3 +133,5 @@ def register_blueprints(app):
|
|||||||
bp = getattr(module, attr)
|
bp = getattr(module, attr)
|
||||||
if isinstance(bp, Blueprint):
|
if isinstance(bp, Blueprint):
|
||||||
app.register_blueprint(bp)
|
app.register_blueprint(bp)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
28
api/config.py
Normal file
28
api/config.py
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
|
from api import require_auth, rate_limits
|
||||||
|
import re
|
||||||
|
config_bp = Blueprint('config', __name__, url_prefix='/api/config')
|
||||||
|
|
||||||
|
RATE_LIMIT_REGEX = re.compile(r'^\d+\s?(per\s|/)\s?(second|minute|hour|day)$')
|
||||||
|
|
||||||
|
def is_valid_rate_limit(limit):
|
||||||
|
return bool(RATE_LIMIT_REGEX.match(limit))
|
||||||
|
@config_bp.route('/limits', methods=['GET'])
|
||||||
|
@require_auth(roles=['admin'])
|
||||||
|
def limits():
|
||||||
|
return jsonify(rate_limits), 200
|
||||||
|
|
||||||
|
@config_bp.route('/limits', methods=['PUT'])
|
||||||
|
@require_auth(roles=['admin'])
|
||||||
|
def update_limits():
|
||||||
|
data = request.json
|
||||||
|
if not data or 'endpoint' not in data or 'method' not in data or 'new_limit' not in data:
|
||||||
|
return jsonify({'error': 'Bad request'}), 400
|
||||||
|
key = f"{data['endpoint']} : {data['method']}"
|
||||||
|
if key not in rate_limits:
|
||||||
|
return jsonify({'error': 'endpoint not fount'}), 404
|
||||||
|
if is_valid_rate_limit(data['new_limit']):
|
||||||
|
rate_limits[key] = data['new_limit']
|
||||||
|
return jsonify({"message": "updated"}), 200
|
||||||
|
return jsonify({'error': 'Invalid value'}), 400
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
#api/markdown.py
|
#api/markdown.py
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
|
|
||||||
|
import api
|
||||||
from api import require_auth
|
from api import require_auth
|
||||||
from contexts.RequestContext import RequestContext
|
from contexts.RequestContext import RequestContext
|
||||||
from db import get_db
|
from db import get_db
|
||||||
@@ -12,14 +13,14 @@ logger = logging.getLogger(__name__)
|
|||||||
markdown_bp = Blueprint('markdown', __name__, url_prefix='/api/markdown')
|
markdown_bp = Blueprint('markdown', __name__, url_prefix='/api/markdown')
|
||||||
|
|
||||||
@markdown_bp.route('/', methods=['GET'])
|
@markdown_bp.route('/', methods=['GET'])
|
||||||
@limiter.limit('5 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def get_markdowns():
|
def get_markdowns():
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
mds = session.query(Markdown).all()
|
mds = session.query(Markdown).all()
|
||||||
return jsonify([md.to_dict() for md in mds]), 200
|
return jsonify([md.to_dict() for md in mds]), 200
|
||||||
|
|
||||||
@markdown_bp.route('/by_path/<int:path_id>', methods=['GET'])
|
@markdown_bp.route('/by_path/<int:path_id>', methods=['GET'])
|
||||||
@limiter.limit('5 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def get_markdowns_by_path(path_id):
|
def get_markdowns_by_path(path_id):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
markdowns = session.query(Markdown).filter(Markdown.path_id == path_id).all()
|
markdowns = session.query(Markdown).filter(Markdown.path_id == path_id).all()
|
||||||
@@ -28,7 +29,7 @@ def get_markdowns_by_path(path_id):
|
|||||||
|
|
||||||
|
|
||||||
@markdown_bp.route('/<int:markdown_id>', methods=['GET'])
|
@markdown_bp.route('/<int:markdown_id>', methods=['GET'])
|
||||||
@limiter.limit('120 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def get_markdown(markdown_id):
|
def get_markdown(markdown_id):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
markdown = session.query(Markdown).get(markdown_id)
|
markdown = session.query(Markdown).get(markdown_id)
|
||||||
@@ -38,7 +39,7 @@ def get_markdown(markdown_id):
|
|||||||
|
|
||||||
@markdown_bp.route('/', methods=['POST'])
|
@markdown_bp.route('/', methods=['POST'])
|
||||||
@require_auth(roles=['admin', 'creator'])
|
@require_auth(roles=['admin', 'creator'])
|
||||||
@limiter.limit('20 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def create_markdown():
|
def create_markdown():
|
||||||
data = request.json
|
data = request.json
|
||||||
title = data.get('title')
|
title = data.get('title')
|
||||||
@@ -60,7 +61,7 @@ def create_markdown():
|
|||||||
|
|
||||||
@markdown_bp.route('/<int:markdown_id>', methods=['PUT'])
|
@markdown_bp.route('/<int:markdown_id>', methods=['PUT'])
|
||||||
@require_auth(roles=['admin', 'creator'])
|
@require_auth(roles=['admin', 'creator'])
|
||||||
@limiter.limit('20 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def update_markdown(markdown_id):
|
def update_markdown(markdown_id):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
markdown = session.query(Markdown).get(markdown_id)
|
markdown = session.query(Markdown).get(markdown_id)
|
||||||
@@ -75,7 +76,7 @@ def update_markdown(markdown_id):
|
|||||||
|
|
||||||
@markdown_bp.route('/<int:markdown_id>', methods=['DELETE'])
|
@markdown_bp.route('/<int:markdown_id>', methods=['DELETE'])
|
||||||
@require_auth(roles=['admin'])
|
@require_auth(roles=['admin'])
|
||||||
@limiter.limit('20 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def delete_markdown(markdown_id):
|
def delete_markdown(markdown_id):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
markdown = session.query(Markdown).get(markdown_id)
|
markdown = session.query(Markdown).get(markdown_id)
|
||||||
|
|||||||
14
api/path.py
14
api/path.py
@@ -1,4 +1,6 @@
|
|||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
|
|
||||||
|
import api
|
||||||
from api import require_auth
|
from api import require_auth
|
||||||
from db import get_db
|
from db import get_db
|
||||||
from db.models.Markdown import Markdown
|
from db.models.Markdown import Markdown
|
||||||
@@ -10,14 +12,14 @@ logger = logging.getLogger(__name__)
|
|||||||
path_bp = Blueprint('path', __name__, url_prefix='/api/path')
|
path_bp = Blueprint('path', __name__, url_prefix='/api/path')
|
||||||
|
|
||||||
@path_bp.route('/', methods=['GET'])
|
@path_bp.route('/', methods=['GET'])
|
||||||
@limiter.limit('5 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def get_root_paths():
|
def get_root_paths():
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
paths = session.query(Path).filter(Path.parent_id == 1)
|
paths = session.query(Path).filter(Path.parent_id == 1)
|
||||||
return jsonify([pth.to_dict() for pth in paths]), 200
|
return jsonify([pth.to_dict() for pth in paths]), 200
|
||||||
|
|
||||||
@path_bp.route('/<int:path_id>', methods=['GET'])
|
@path_bp.route('/<int:path_id>', methods=['GET'])
|
||||||
@limiter.limit('5 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def get_path(path_id):
|
def get_path(path_id):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
path = session.query(Path).get(path_id)
|
path = session.query(Path).get(path_id)
|
||||||
@@ -26,14 +28,14 @@ def get_path(path_id):
|
|||||||
return jsonify(path.to_dict()), 200
|
return jsonify(path.to_dict()), 200
|
||||||
|
|
||||||
@path_bp.route('/parent/<int:parent_id>', methods=['GET'])
|
@path_bp.route('/parent/<int:parent_id>', methods=['GET'])
|
||||||
@limiter.limit('5 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def get_path_by_parent(parent_id):
|
def get_path_by_parent(parent_id):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
paths = session.query(Path).filter(Path.parent_id == parent_id).all()
|
paths = session.query(Path).filter(Path.parent_id == parent_id).all()
|
||||||
return jsonify([pth.to_dict() for pth in paths]), 200
|
return jsonify([pth.to_dict() for pth in paths]), 200
|
||||||
|
|
||||||
@path_bp.route('/', methods=['POST'])
|
@path_bp.route('/', methods=['POST'])
|
||||||
@limiter.limit('60 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
@require_auth(roles=['admin', 'creator'])
|
@require_auth(roles=['admin', 'creator'])
|
||||||
def create_path():
|
def create_path():
|
||||||
data = request.json
|
data = request.json
|
||||||
@@ -50,7 +52,7 @@ def create_path():
|
|||||||
return jsonify(new_path.to_dict()), 201
|
return jsonify(new_path.to_dict()), 201
|
||||||
|
|
||||||
@path_bp.route('/<int:path_id>', methods=['PUT'])
|
@path_bp.route('/<int:path_id>', methods=['PUT'])
|
||||||
@limiter.limit('30 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
@require_auth(roles=['admin'])
|
@require_auth(roles=['admin'])
|
||||||
def update_path(path_id):
|
def update_path(path_id):
|
||||||
data = request.json
|
data = request.json
|
||||||
@@ -68,7 +70,7 @@ def update_path(path_id):
|
|||||||
return jsonify(path.to_dict()), 200
|
return jsonify(path.to_dict()), 200
|
||||||
|
|
||||||
@path_bp.route('/<int:path_id>', methods=['DELETE'])
|
@path_bp.route('/<int:path_id>', methods=['DELETE'])
|
||||||
@limiter.limit('60 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
@require_auth(roles=['admin'])
|
@require_auth(roles=['admin'])
|
||||||
def delete_path(path_id):
|
def delete_path(path_id):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#api/resource.py
|
#api/resource.py
|
||||||
|
import api
|
||||||
from flask import Blueprint, jsonify, request
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
from contexts.RequestContext import RequestContext
|
from contexts.RequestContext import RequestContext
|
||||||
from db import get_db
|
from db import get_db
|
||||||
from db.models.Resource import Resource
|
from db.models.Resource import Resource
|
||||||
@@ -9,7 +9,7 @@ import logging
|
|||||||
resource_bp = Blueprint('resource', __name__, url_prefix='/api/resource')
|
resource_bp = Blueprint('resource', __name__, url_prefix='/api/resource')
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@resource_bp.route('/<identifier>', methods=['GET'])
|
@resource_bp.route('/<identifier>', methods=['GET'])
|
||||||
@limiter.limit('10 per second')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def get_resource(identifier):
|
def get_resource(identifier):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
resource = session.query(Resource).get(identifier)
|
resource = session.query(Resource).get(identifier)
|
||||||
@@ -21,7 +21,7 @@ def get_resource(identifier):
|
|||||||
|
|
||||||
@resource_bp.route('/', methods=['POST'])
|
@resource_bp.route('/', methods=['POST'])
|
||||||
@require_auth(roles=["admin", "creator"])
|
@require_auth(roles=["admin", "creator"])
|
||||||
@limiter.limit('20 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def create_resource():
|
def create_resource():
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
identifier = data.get('id')
|
identifier = data.get('id')
|
||||||
@@ -43,7 +43,7 @@ def create_resource():
|
|||||||
|
|
||||||
@resource_bp.route('/<identifier>', methods=['DELETE'])
|
@resource_bp.route('/<identifier>', methods=['DELETE'])
|
||||||
@require_auth(roles=["admin"])
|
@require_auth(roles=["admin"])
|
||||||
@limiter.limit('20 per minute')
|
@limiter.limit(api.get_rate_limit)
|
||||||
def delete_resource(identifier):
|
def delete_resource(identifier):
|
||||||
with get_db() as session:
|
with get_db() as session:
|
||||||
resource = session.query(Resource).get(identifier)
|
resource = session.query(Resource).get(identifier)
|
||||||
@@ -54,3 +54,4 @@ def delete_resource(identifier):
|
|||||||
session.delete(resource)
|
session.delete(resource)
|
||||||
session.commit()
|
session.commit()
|
||||||
return jsonify({"message": "Resource deleted"}), 200
|
return jsonify({"message": "Resource deleted"}), 200
|
||||||
|
|
||||||
3
app.py
3
app.py
@@ -44,7 +44,10 @@ def log_request():
|
|||||||
logger.info(f"Request received: {request.method} {request.path} from {request.remote_addr}")
|
logger.info(f"Request received: {request.method} {request.path} from {request.remote_addr}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
api.init_rate_limits(app)
|
||||||
#logger.info("Starting app")
|
#logger.info("Starting app")
|
||||||
pprint(env_provider.summerize())
|
pprint(env_provider.summerize())
|
||||||
app.run(host='0.0.0.0', port=5000)
|
app.run(host='0.0.0.0', port=5000)
|
||||||
|
|||||||
Reference in New Issue
Block a user