fastapi-rate-limiter-plugin 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ from fastapi_rate_limiter.backend import (
2
+ COUNT_SCRIPT,
3
+ Identifier,
4
+ RateLimiterBackend,
5
+ client_ip_and_path,
6
+ )
7
+ from fastapi_rate_limiter.depends import (
8
+ BaseRateLimiter,
9
+ RateLimiter,
10
+ WebSocketRateLimiter,
11
+ )
12
+
13
+ __all__ = [
14
+ "COUNT_SCRIPT",
15
+ "BaseRateLimiter",
16
+ "Identifier",
17
+ "RateLimiter",
18
+ "RateLimiterBackend",
19
+ "WebSocketRateLimiter",
20
+ "client_ip_and_path",
21
+ ]
@@ -0,0 +1,80 @@
1
+ from collections.abc import Awaitable, Callable
2
+
3
+ from redis.asyncio import Redis
4
+ from redis.exceptions import NoScriptError
5
+ from starlette.requests import HTTPConnection
6
+
7
+ COUNT_SCRIPT = """
8
+ local key = KEYS[1]
9
+ local limit = tonumber(ARGV[1])
10
+ local window_ms = ARGV[2]
11
+
12
+ local current = tonumber(redis.call('GET', key) or "0")
13
+ if current >= limit then
14
+ return redis.call('PTTL', key)
15
+ end
16
+
17
+ if current == 0 then
18
+ redis.call('SET', key, 1, 'PX', window_ms)
19
+ else
20
+ redis.call('INCR', key)
21
+ end
22
+ return 0
23
+ """
24
+
25
+ Identifier = Callable[[HTTPConnection], Awaitable[str]]
26
+
27
+
28
+ async def client_ip_and_path(connection: HTTPConnection) -> str:
29
+ forwarded = connection.headers.get("X-Forwarded-For")
30
+ if forwarded:
31
+ host = forwarded.split(",")[0].strip()
32
+ elif connection.client is not None:
33
+ host = connection.client.host
34
+ else:
35
+ host = "unknown"
36
+ return f"{host}:{connection.scope['path']}"
37
+
38
+
39
+ class RateLimiterBackend:
40
+ redis: Redis | None = None
41
+ prefix: str = "rate-limit"
42
+ identifier: Identifier = client_ip_and_path
43
+ _script_sha: str | None = None
44
+
45
+ @classmethod
46
+ async def setup(
47
+ cls,
48
+ redis: Redis,
49
+ prefix: str = "rate-limit",
50
+ identifier: Identifier | None = None,
51
+ ) -> None:
52
+ cls.redis = redis
53
+ cls.prefix = prefix
54
+ cls.identifier = identifier or client_ip_and_path
55
+ cls._script_sha = await redis.script_load(COUNT_SCRIPT)
56
+
57
+ @classmethod
58
+ async def close(cls) -> None:
59
+ cls.redis = None
60
+ cls._script_sha = None
61
+
62
+ @classmethod
63
+ async def count(cls, key: str, times: int, window_ms: int) -> int:
64
+ if cls.redis is None or cls._script_sha is None:
65
+ raise RuntimeError(
66
+ "RateLimiterBackend.setup() has to run before the first request, "
67
+ "usually from the lifespan of the application.",
68
+ )
69
+
70
+ try:
71
+ return await cls.redis.evalsha(cls._script_sha, 1, key, str(times), str(window_ms))
72
+ except NoScriptError:
73
+ cls._script_sha = await cls.redis.script_load(COUNT_SCRIPT)
74
+ return await cls.redis.evalsha(cls._script_sha, 1, key, str(times), str(window_ms))
75
+
76
+ @classmethod
77
+ async def reset_in_ms(cls, key: str) -> int:
78
+ if cls.redis is None:
79
+ return 0
80
+ return max(await cls.redis.pttl(key), 0)
@@ -0,0 +1,62 @@
1
+ import math
2
+
3
+ from starlette.exceptions import HTTPException
4
+ from starlette.requests import HTTPConnection, Request
5
+ from starlette.responses import Response
6
+ from starlette.status import HTTP_429_TOO_MANY_REQUESTS
7
+ from starlette.websockets import WebSocket
8
+
9
+ from fastapi_rate_limiter.backend import Identifier, RateLimiterBackend
10
+
11
+
12
+ class BaseRateLimiter:
13
+ def __init__(
14
+ self,
15
+ times: int = 1,
16
+ milliseconds: int = 0,
17
+ seconds: int = 0,
18
+ minutes: int = 0,
19
+ hours: int = 0,
20
+ identifier: Identifier | None = None,
21
+ ) -> None:
22
+ window_ms = milliseconds + 1000 * seconds + 60_000 * minutes + 3_600_000 * hours
23
+ if times < 1:
24
+ raise ValueError("times has to be at least 1")
25
+ if window_ms < 1:
26
+ raise ValueError("the window has to be at least one millisecond")
27
+
28
+ self.times = times
29
+ self.window_ms = window_ms
30
+ self.identifier = identifier
31
+
32
+ async def key_for(self, connection: HTTPConnection) -> str:
33
+ identifier = self.identifier or RateLimiterBackend.identifier
34
+ caller = await identifier(connection)
35
+ return f"{RateLimiterBackend.prefix}:{caller}:{self.times}:{self.window_ms}"
36
+
37
+ async def spend(self, key: str) -> None:
38
+ retry_after_ms = await RateLimiterBackend.count(key, self.times, self.window_ms)
39
+ if retry_after_ms:
40
+ raise HTTPException(
41
+ status_code=HTTP_429_TOO_MANY_REQUESTS,
42
+ detail="Too Many Requests",
43
+ headers={"Retry-After": str(math.ceil(retry_after_ms / 1000))},
44
+ )
45
+
46
+
47
+ class RateLimiter(BaseRateLimiter):
48
+ async def __call__(self, request: Request, response: Response) -> None:
49
+ key = await self.key_for(request)
50
+ await self.spend(key)
51
+
52
+ reset_in_ms = await RateLimiterBackend.reset_in_ms(key)
53
+ request.state.rate_limit_reset_in_seconds = math.ceil(reset_in_ms / 1000)
54
+ response.headers["X-RateLimit-Limit"] = str(self.times)
55
+
56
+
57
+ class WebSocketRateLimiter(BaseRateLimiter):
58
+ async def __call__(self, websocket: WebSocket, context_key: str = "") -> None:
59
+ key = await self.key_for(websocket)
60
+ if context_key:
61
+ key = f"{key}:{context_key}"
62
+ await self.spend(key)
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-rate-limiter-plugin
3
+ Version: 1.0.0
4
+ Summary: Redis backed rate limiting dependency for FastAPI and Starlette
5
+ Keywords: fastapi,starlette,rate-limit,throttling,redis
6
+ Author: bb-soft
7
+ Author-email: bb-soft <noreply@k1core.tech>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Framework :: FastAPI
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Internet :: WWW/HTTP
14
+ Requires-Dist: redis>=5
15
+ Requires-Dist: starlette>=0.37
16
+ Requires-Python: >=3.12
17
+ Project-URL: Repository, https://github.com/k1core-ltd/fastapi-rate-limiter
18
+ Description-Content-Type: text/markdown
19
+
20
+ # fastapi-rate-limiter-plugin
21
+
22
+ Redis backed rate limiting for FastAPI and Starlette, as a dependency on the
23
+ endpoints that need it.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pip install fastapi-rate-limiter-plugin
29
+ ```
30
+
31
+ ## Use
32
+
33
+ Point the backend at redis once, from the lifespan of the application:
34
+
35
+ ```python
36
+ import contextlib
37
+
38
+ import redis.asyncio
39
+ from fastapi import Depends, FastAPI
40
+ from fastapi_rate_limiter import RateLimiter, RateLimiterBackend
41
+
42
+
43
+ @contextlib.asynccontextmanager
44
+ async def lifespan(_: FastAPI):
45
+ await RateLimiterBackend.setup(redis.asyncio.from_url("redis://localhost"))
46
+ yield
47
+ await RateLimiterBackend.close()
48
+
49
+
50
+ app = FastAPI(lifespan=lifespan)
51
+
52
+
53
+ @app.post("/resend", dependencies=[Depends(RateLimiter(times=5, seconds=60))])
54
+ async def resend() -> dict:
55
+ return {"sent": True}
56
+ ```
57
+
58
+ A caller over the limit gets a `429` with a `Retry-After` header. A request that
59
+ gets through leaves `request.state.rate_limit_reset_in_seconds`, so an endpoint
60
+ can tell the caller when the window resets.
61
+
62
+ Callers are told apart by `X-Forwarded-For`, falling back to the peer address,
63
+ together with the path. Pass `identifier` to `setup` or to a single limiter to
64
+ count by something else, such as a tenant or an API key:
65
+
66
+ ```python
67
+ async def by_tenant(connection: HTTPConnection) -> str:
68
+ return connection.headers.get("X-Tenant-Id", "unknown")
69
+
70
+
71
+ RateLimiter(times=100, hours=1, identifier=by_tenant)
72
+ ```
73
+
74
+ ## Websockets
75
+
76
+ `WebSocketRateLimiter` counts messages rather than connections, and takes a
77
+ context key so one socket can hold several independent limits:
78
+
79
+ ```python
80
+ limiter = WebSocketRateLimiter(times=10, seconds=5)
81
+
82
+
83
+ @app.websocket("/ws")
84
+ async def ws(websocket: WebSocket):
85
+ await websocket.accept()
86
+ while True:
87
+ message = await websocket.receive_text()
88
+ await limiter(websocket, context_key=message)
89
+ ```
90
+
91
+ ## Notes
92
+
93
+ Counting is a single Lua script, so a window is counted atomically and every
94
+ instance of the service counts one caller together. The script is reloaded by
95
+ itself when redis drops its cache after a restart.
96
+
97
+ ## License
98
+
99
+ MIT
@@ -0,0 +1,7 @@
1
+ fastapi_rate_limiter/__init__.py,sha256=IVdgolRBD_BVFOis7JWqb54J4s5SN97PARSvTwdqV80,411
2
+ fastapi_rate_limiter/backend.py,sha256=p9WN_Rfm3e8ELz03o51n8srwLz5PNdJrhcIoCAOe0V8,2359
3
+ fastapi_rate_limiter/depends.py,sha256=r0jLhbf649YuD24N_9ylV1vmn47kNYcrOiLu80kmi3k,2272
4
+ fastapi_rate_limiter_plugin-1.0.0.dist-info/licenses/LICENSE,sha256=OSb23rV5PGSd-vxTBwBD0-rhuIZjpuZ-dyn5B2SQnyc,1068
5
+ fastapi_rate_limiter_plugin-1.0.0.dist-info/WHEEL,sha256=3iQx15CyXwGi4dbygedzA4M5T1eqO_SjwdPfUmqt2Cw,81
6
+ fastapi_rate_limiter_plugin-1.0.0.dist-info/METADATA,sha256=oXN6hrSSH-3jGIp95JE6C43sx5kQ5ltmghk-bm-SB24,2739
7
+ fastapi_rate_limiter_plugin-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.24
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 K1 Core Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.