Skip to content

Commit f14e552

Browse files
committed
rate limit redis pool and initial setup
1 parent 394c791 commit f14e552

File tree

6 files changed

+34
-5
lines changed

6 files changed

+34
-5
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464
- [ ] Docs for other databases (MysQL, SQLite)
6565

6666
#### Features
67-
- [ ] Add a Rate Limiter decorator
67+
- [ ] Add a Rate Limiter dependency
6868
- [ ] Add mongoDB support
6969

7070
#### Tests

src/app/api/dependencies.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)], db: An
3535

3636
return user
3737

38-
def get_current_superuser(current_user: Annotated[User, Depends(get_current_user)]) -> User:
38+
async def get_current_superuser(current_user: Annotated[User, Depends(get_current_user)]) -> User:
3939
if not current_user.is_superuser:
4040
raise privileges_exception
4141

src/app/core/cache.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
from typing import Callable, Union, List, Dict, Any
22
import functools
33
import json
4-
from uuid import UUID
5-
from datetime import datetime
64
import re
75

86
from fastapi import Request, Response

src/app/core/config.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ class RedisQueueSettings(BaseSettings):
8484
REDIS_QUEUE_PORT: str = config("REDIS_QUEUE_PORT", default=6379)
8585

8686

87+
class RedisRateLimiterSettings(BaseSettings):
88+
REDIS_RATE_LIMITER_HOST: str = config("REDIS_RATE_LIMITER_HOST", default="localhost")
89+
REDIS_RATE_LIMITER_PORT: int = config("REDIS_RATE_LIMITER_PORT", default=6379)
90+
REDIS_RATE_LIMITER_URL: str = f"redis://{REDIS_RATE_LIMITER_HOST}:{REDIS_RATE_LIMITER_PORT}"
91+
92+
8793
class EnvironmentOption(Enum):
8894
LOCAL = "local"
8995
STAGING = "staging"
@@ -103,6 +109,7 @@ class Settings(
103109
RedisCacheSettings,
104110
ClientSideCacheSettings,
105111
RedisQueueSettings,
112+
RedisRateLimiterSettings,
106113
EnvironmentSettings
107114
):
108115
pass

src/app/core/rate_limit.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import time
2+
3+
from fastapi import HTTPException, Request, Depends, status
4+
from redis.asyncio import Redis, ConnectionPool
5+
6+
from app.api.dependencies import get_current_user
7+
8+
pool: ConnectionPool | None = None
9+
client: Redis | None = None

src/app/core/setup.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99

1010
from app.api.dependencies import get_current_superuser
11-
from app.core import cache, queue
11+
from app.core import cache, queue, rate_limit
1212
from app.core.config import settings
1313
from app.core.database import Base
1414
from app.core.database import async_engine as engine
@@ -18,6 +18,7 @@
1818
AppSettings,
1919
ClientSideCacheSettings,
2020
RedisQueueSettings,
21+
RedisRateLimiterSettings,
2122
EnvironmentOption,
2223
EnvironmentSettings
2324
)
@@ -49,6 +50,16 @@ async def close_redis_queue_pool():
4950
await queue.pool.aclose()
5051

5152

53+
# -------------- rate limit --------------
54+
async def create_redis_rate_limit_pool():
55+
rate_limit.pool = redis.ConnectionPool.from_url(settings.REDIS_RATE_LIMIT_URL)
56+
rate_limit.client = redis.Redis.from_pool(rate_limit.pool)
57+
58+
59+
async def close_redis_rate_limit_pool():
60+
await rate_limit.client.aclose()
61+
62+
5263
# -------------- application --------------
5364
async def set_threadpool_tokens(number_of_tokens=100):
5465
limiter = anyio.to_thread.current_default_thread_limiter()
@@ -133,6 +144,10 @@ def create_application(router: APIRouter, settings, **kwargs) -> FastAPI:
133144
application.add_event_handler("startup", create_redis_queue_pool)
134145
application.add_event_handler("shutdown", close_redis_queue_pool)
135146

147+
if isinstance(settings, RedisRateLimiterSettings):
148+
application.add_event_handler("startup", create_redis_rate_limit_pool)
149+
application.add_event_handler("shutdown", close_redis_rate_limit_pool)
150+
136151
if isinstance(settings, EnvironmentSettings):
137152
if settings.ENVIRONMENT != EnvironmentOption.PRODUCTION:
138153
docs_router = APIRouter()

0 commit comments

Comments
 (0)