fastapi-rate-limiter-plugin 1.0.0__tar.gz
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.
- fastapi_rate_limiter_plugin-1.0.0/LICENSE +21 -0
- fastapi_rate_limiter_plugin-1.0.0/PKG-INFO +99 -0
- fastapi_rate_limiter_plugin-1.0.0/README.md +80 -0
- fastapi_rate_limiter_plugin-1.0.0/pyproject.toml +67 -0
- fastapi_rate_limiter_plugin-1.0.0/pyproject.toml.orig +48 -0
- fastapi_rate_limiter_plugin-1.0.0/src/fastapi_rate_limiter/__init__.py +21 -0
- fastapi_rate_limiter_plugin-1.0.0/src/fastapi_rate_limiter/backend.py +80 -0
- fastapi_rate_limiter_plugin-1.0.0/src/fastapi_rate_limiter/depends.py +62 -0
|
@@ -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.
|
|
@@ -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,80 @@
|
|
|
1
|
+
# fastapi-rate-limiter-plugin
|
|
2
|
+
|
|
3
|
+
Redis backed rate limiting for FastAPI and Starlette, as a dependency on the
|
|
4
|
+
endpoints that need it.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install fastapi-rate-limiter-plugin
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Use
|
|
13
|
+
|
|
14
|
+
Point the backend at redis once, from the lifespan of the application:
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
import contextlib
|
|
18
|
+
|
|
19
|
+
import redis.asyncio
|
|
20
|
+
from fastapi import Depends, FastAPI
|
|
21
|
+
from fastapi_rate_limiter import RateLimiter, RateLimiterBackend
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@contextlib.asynccontextmanager
|
|
25
|
+
async def lifespan(_: FastAPI):
|
|
26
|
+
await RateLimiterBackend.setup(redis.asyncio.from_url("redis://localhost"))
|
|
27
|
+
yield
|
|
28
|
+
await RateLimiterBackend.close()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
app = FastAPI(lifespan=lifespan)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@app.post("/resend", dependencies=[Depends(RateLimiter(times=5, seconds=60))])
|
|
35
|
+
async def resend() -> dict:
|
|
36
|
+
return {"sent": True}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
A caller over the limit gets a `429` with a `Retry-After` header. A request that
|
|
40
|
+
gets through leaves `request.state.rate_limit_reset_in_seconds`, so an endpoint
|
|
41
|
+
can tell the caller when the window resets.
|
|
42
|
+
|
|
43
|
+
Callers are told apart by `X-Forwarded-For`, falling back to the peer address,
|
|
44
|
+
together with the path. Pass `identifier` to `setup` or to a single limiter to
|
|
45
|
+
count by something else, such as a tenant or an API key:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
async def by_tenant(connection: HTTPConnection) -> str:
|
|
49
|
+
return connection.headers.get("X-Tenant-Id", "unknown")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
RateLimiter(times=100, hours=1, identifier=by_tenant)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Websockets
|
|
56
|
+
|
|
57
|
+
`WebSocketRateLimiter` counts messages rather than connections, and takes a
|
|
58
|
+
context key so one socket can hold several independent limits:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
limiter = WebSocketRateLimiter(times=10, seconds=5)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@app.websocket("/ws")
|
|
65
|
+
async def ws(websocket: WebSocket):
|
|
66
|
+
await websocket.accept()
|
|
67
|
+
while True:
|
|
68
|
+
message = await websocket.receive_text()
|
|
69
|
+
await limiter(websocket, context_key=message)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Notes
|
|
73
|
+
|
|
74
|
+
Counting is a single Lua script, so a window is counted atomically and every
|
|
75
|
+
instance of the service counts one caller together. The script is reloaded by
|
|
76
|
+
itself when redis drops its cache after a restart.
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
MIT
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fastapi-rate-limiter-plugin"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Redis backed rate limiting dependency for FastAPI and Starlette"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.12"
|
|
9
|
+
keywords = [
|
|
10
|
+
"fastapi",
|
|
11
|
+
"starlette",
|
|
12
|
+
"rate-limit",
|
|
13
|
+
"throttling",
|
|
14
|
+
"redis",
|
|
15
|
+
]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Framework :: FastAPI",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"redis>=5",
|
|
24
|
+
"starlette>=0.37",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[[project.authors]]
|
|
28
|
+
name = "bb-soft"
|
|
29
|
+
email = "noreply@k1core.tech"
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Repository = "https://github.com/k1core-ltd/fastapi-rate-limiter"
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["uv_build>=0.9,<0.13"]
|
|
36
|
+
build-backend = "uv_build"
|
|
37
|
+
|
|
38
|
+
[tool.uv.build-backend]
|
|
39
|
+
module-name = "fastapi_rate_limiter"
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
testpaths = ["tests"]
|
|
43
|
+
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
line-length = 100
|
|
46
|
+
|
|
47
|
+
[tool.ruff.lint]
|
|
48
|
+
extend-select = [
|
|
49
|
+
"UP",
|
|
50
|
+
"E",
|
|
51
|
+
"W",
|
|
52
|
+
"I",
|
|
53
|
+
"N",
|
|
54
|
+
"ANN",
|
|
55
|
+
"B",
|
|
56
|
+
"C4",
|
|
57
|
+
"RET",
|
|
58
|
+
"SIM",
|
|
59
|
+
"TID",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
[dependency-groups]
|
|
63
|
+
dev = [
|
|
64
|
+
"pytest>=9.1.1",
|
|
65
|
+
"pre-commit>=4.6.2",
|
|
66
|
+
"ruff>=0.13",
|
|
67
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fastapi-rate-limiter-plugin"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Redis backed rate limiting dependency for FastAPI and Starlette"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "bb-soft", email = "noreply@k1core.tech" },
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
keywords = ["fastapi", "starlette", "rate-limit", "throttling", "redis"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Framework :: FastAPI",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"redis>=5",
|
|
21
|
+
"starlette>=0.37",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Repository = "https://github.com/k1core-ltd/fastapi-rate-limiter"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["uv_build>=0.9,<0.13"]
|
|
29
|
+
build-backend = "uv_build"
|
|
30
|
+
|
|
31
|
+
[tool.uv.build-backend]
|
|
32
|
+
module-name = "fastapi_rate_limiter"
|
|
33
|
+
|
|
34
|
+
[dependency-groups]
|
|
35
|
+
dev = [
|
|
36
|
+
"pytest>=9.1.1",
|
|
37
|
+
"pre-commit>=4.6.2",
|
|
38
|
+
"ruff>=0.13",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
testpaths = ["tests"]
|
|
43
|
+
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
line-length = 100
|
|
46
|
+
|
|
47
|
+
[tool.ruff.lint]
|
|
48
|
+
extend-select = ["UP", "E", "W", "I", "N", "ANN", "B", "C4", "RET", "SIM", "TID"]
|
|
@@ -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)
|