-
Notifications
You must be signed in to change notification settings - Fork 42
limiter v2 #243
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
Open
zhufengthehemera
wants to merge
7
commits into
pre-release/v0.6.0
Choose a base branch
from
feature/api-rate-limit
base: pre-release/v0.6.0
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
limiter v2 #243
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a7989f6
limiter v2
zhufengthehemera b3b1a75
update
zhufengthehemera 32f2e50
add expires at
zhufengthehemera a406201
add readme
zhufengthehemera b8bb6ff
fmt
zhufengthehemera 035ff03
fmt
zhufengthehemera 90634c0
update readme
zhufengthehemera File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| # Limiter V2 | ||
|
|
||
| ## Usage | ||
|
|
||
| note: | ||
|
|
||
| **limiter_v2.limit decorator must be used before cache.cached decorator** | ||
|
|
||
|
|
||
| ```python | ||
| from limiter_v2 import limiter_v2, require_api_key, get_limits | ||
|
|
||
|
|
||
| # require_api_key, user default limits | ||
| @explorer_namespace.route("/v1/some_resource") | ||
| class SomeResource(Resource): | ||
| @require_api_key | ||
| @cache.cached(timeout=300, query_string=True) | ||
| def get(self): | ||
| return {"message": "Hello, world!"}, 200 | ||
|
|
||
|
|
||
| # require_api_key, user custom limits | ||
| @explorer_namespace.route("/v1/some_resource") | ||
| class SomeResource(Resource): | ||
| @require_api_key | ||
| @limiter_v2.limit(get_limits) | ||
| @cache.cached(timeout=300, query_string=True) | ||
| def get(self): | ||
| return {"message": "Hello, world!"}, 200 | ||
|
|
||
|
|
||
| # require_api_key, user custom limits with cost | ||
| @explorer_namespace.route("/v1/some_resource") | ||
| class SomeResource(Resource): | ||
| @require_api_key | ||
| @limiter_v2.limit(get_limits, cost=2) | ||
| @cache.cached(timeout=300, query_string=True) | ||
| def get(self): | ||
| return {"message": "Hello, world!"}, 200 | ||
|
|
||
| # require_api_key, user custom limits with cost, if user has no limits, use default limits | ||
| @explorer_namespace.route("/v1/some_resource") | ||
| class SomeResource(Resource): | ||
| @require_api_key | ||
| @limiter_v2.limit(get_limits, cost=2, override_defaults=False) | ||
| @cache.cached(timeout=300, query_string=True) | ||
| def get(self): | ||
| return {"message": "Hello, world!"}, 200 | ||
| ``` | ||
|
|
||
| ## add new limits | ||
|
|
||
| generate new api key and insert into db | ||
|
|
||
| limits format: | ||
| ``` | ||
| 1/second, 100/hour | ||
| 1000/day | ||
| 30 per minute | ||
| ``` | ||
| multiple limits are supported, use comma to separate | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| from datetime import datetime, timezone | ||
| from functools import wraps | ||
|
|
||
| from flask import jsonify, make_response, request | ||
| from flask_limiter import Limiter | ||
|
|
||
| from api.app import cache | ||
| from common.models import db | ||
| from common.models.limiter import ApiKey | ||
|
|
||
|
|
||
| def get_header_api_key(): | ||
| return request.headers.get("X-API-KEY", "") | ||
|
|
||
|
|
||
| limiter_v2 = Limiter( | ||
| key_func=get_header_api_key, | ||
| default_limits=["100 per hour"], | ||
| storage_uri="memory://", | ||
| ) | ||
|
|
||
|
|
||
| def require_api_key(f): | ||
| @wraps(f) | ||
| def decorated(*args, **kwargs): | ||
| api_key = get_header_api_key() | ||
| if not get_api_key(api_key): | ||
| return make_response(jsonify({"error": "Invalid API key"}), 403) | ||
| return f(*args, **kwargs) | ||
|
|
||
| return decorated | ||
|
|
||
|
|
||
| def get_api_key(api_key): | ||
| cache_key = f"ak_{api_key}" | ||
| api_key_from_cache = cache.cache.get(cache_key) | ||
| if api_key_from_cache: | ||
| # if id is -1, api key not found in db | ||
| if api_key_from_cache.id == -1: | ||
| return None | ||
| return api_key_from_cache | ||
|
|
||
| api_key_from_db = ( | ||
| db.session.query(ApiKey) | ||
| .filter(ApiKey.api_key == api_key, ApiKey.expires_at > datetime.now(timezone.utc)) | ||
| .first() | ||
| ) | ||
|
|
||
| if api_key_from_db: | ||
| cache.cache.set(cache_key, api_key_from_db, 600) | ||
| return api_key_from_db | ||
|
|
||
| # if api key not found in db, set it in cache to avoid future db hits | ||
| cache.cache.set(cache_key, ApiKey(id=-1), 300) | ||
| return None | ||
|
|
||
|
|
||
| def get_limits(): | ||
| api_key = get_header_api_key() | ||
| api_key_model = get_api_key(api_key) | ||
|
|
||
| if api_key_model: | ||
| return api_key_model.limits | ||
|
|
||
| return [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| from sqlalchemy import TEXT, Column, func | ||
| from sqlalchemy.dialects.postgresql import BIGINT, JSONB, TIMESTAMP, VARCHAR | ||
|
|
||
| from common.models import HemeraModel | ||
|
|
||
|
|
||
| class ApiKey(HemeraModel): | ||
| __tablename__ = "api_key" | ||
|
|
||
| id = Column(BIGINT, primary_key=True, autoincrement=True) | ||
| api_key = Column(VARCHAR(255), unique=True) | ||
| limits = Column(TEXT) | ||
| expires_at = Column(TIMESTAMP) | ||
| description = Column(VARCHAR(255)) | ||
| created_at = Column(TIMESTAMP, default=func.now()) | ||
| updated_at = Column(TIMESTAMP, default=func.now(), onupdate=func.now()) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this limit apply per api key?