fastapi-ratelimits 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bernardo Gomes
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,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-ratelimits
3
+ Version: 0.1.0
4
+ Summary: Async rate limiting for FastAPI dependencies, powered by limits
5
+ Author: Bernardo Gomes
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Dist: fastapi>=0.163.1,<1
9
+ Requires-Dist: limits>=5.8,<6
10
+ Requires-Dist: redis>=5.2,<8 ; extra == 'redis'
11
+ Requires-Python: >=3.11
12
+ Project-URL: Repository, https://github.com/Bernardoow/fastapi-ratelimits
13
+ Project-URL: Issues, https://github.com/Bernardoow/fastapi-ratelimits/issues
14
+ Provides-Extra: redis
15
+ Description-Content-Type: text/markdown
16
+
17
+ # fastapi-ratelimits
18
+
19
+ Asynchronous rate limiting for HTTP APIs built with FastAPI. Define limits as
20
+ FastAPI dependencies and share counters across workers with Redis. Requires
21
+ Python 3.11 or newer.
22
+
23
+ [English documentation](https://bernardoow.github.io/fastapi-ratelimits/)
24
+ · [Documentação em português](https://bernardoow.github.io/fastapi-ratelimits/pt-br/)
25
+
26
+ Install the package with `pip install fastapi-ratelimits`. For Redis, use
27
+ `pip install 'fastapi-ratelimits[redis]'`.
28
+
29
+ ```python
30
+ from fastapi import Depends, FastAPI
31
+
32
+ from fastapi_ratelimits import Limiter
33
+
34
+ limiter = Limiter(storage_uri="async+memory://")
35
+ app = FastAPI(lifespan=limiter.lifespan)
36
+
37
+
38
+ @app.get("/orders", dependencies=[Depends(limiter.limit("2/minute"))])
39
+ async def orders():
40
+ return {"orders": []}
41
+ ```
42
+
43
+ In this single-process example, each client IP gets two requests per minute to `GET /orders`. The
44
+ [Quickstart](https://bernardoow.github.io/fastapi-ratelimits/quickstart/) shows
45
+ how to run the app and see the `429` response.
46
+
47
+ ## Development
48
+
49
+ ```sh
50
+ uv sync --python 3.11 --extra redis
51
+ uv run --python 3.11 pytest -m 'not redis'
52
+ uv run --python 3.11 mypy
53
+ uv run --python 3.11 ruff check .
54
+ ```
55
+
56
+ For Redis integration tests, use a disposable local server. Set
57
+ `RATELIMITS_TEST_REDIS_URL` to a client URI without the `async+` prefix.
58
+
59
+ ```sh
60
+ RATELIMITS_TEST_REDIS_URL=redis://127.0.0.1:6379/0 uv run --python 3.11 --extra redis pytest
61
+ ```
62
+
63
+ Build both documentation editions in this order. The Portuguese build writes
64
+ to `site/pt-br/` under the English build's output.
65
+
66
+ ```sh
67
+ uv run --locked --no-dev --group docs zensical build --clean --strict
68
+ uv run --locked --no-dev --group docs zensical build --clean --strict --config-file zensical.pt-br.toml
69
+ ```
@@ -0,0 +1,53 @@
1
+ # fastapi-ratelimits
2
+
3
+ Asynchronous rate limiting for HTTP APIs built with FastAPI. Define limits as
4
+ FastAPI dependencies and share counters across workers with Redis. Requires
5
+ Python 3.11 or newer.
6
+
7
+ [English documentation](https://bernardoow.github.io/fastapi-ratelimits/)
8
+ · [Documentação em português](https://bernardoow.github.io/fastapi-ratelimits/pt-br/)
9
+
10
+ Install the package with `pip install fastapi-ratelimits`. For Redis, use
11
+ `pip install 'fastapi-ratelimits[redis]'`.
12
+
13
+ ```python
14
+ from fastapi import Depends, FastAPI
15
+
16
+ from fastapi_ratelimits import Limiter
17
+
18
+ limiter = Limiter(storage_uri="async+memory://")
19
+ app = FastAPI(lifespan=limiter.lifespan)
20
+
21
+
22
+ @app.get("/orders", dependencies=[Depends(limiter.limit("2/minute"))])
23
+ async def orders():
24
+ return {"orders": []}
25
+ ```
26
+
27
+ In this single-process example, each client IP gets two requests per minute to `GET /orders`. The
28
+ [Quickstart](https://bernardoow.github.io/fastapi-ratelimits/quickstart/) shows
29
+ how to run the app and see the `429` response.
30
+
31
+ ## Development
32
+
33
+ ```sh
34
+ uv sync --python 3.11 --extra redis
35
+ uv run --python 3.11 pytest -m 'not redis'
36
+ uv run --python 3.11 mypy
37
+ uv run --python 3.11 ruff check .
38
+ ```
39
+
40
+ For Redis integration tests, use a disposable local server. Set
41
+ `RATELIMITS_TEST_REDIS_URL` to a client URI without the `async+` prefix.
42
+
43
+ ```sh
44
+ RATELIMITS_TEST_REDIS_URL=redis://127.0.0.1:6379/0 uv run --python 3.11 --extra redis pytest
45
+ ```
46
+
47
+ Build both documentation editions in this order. The Portuguese build writes
48
+ to `site/pt-br/` under the English build's output.
49
+
50
+ ```sh
51
+ uv run --locked --no-dev --group docs zensical build --clean --strict
52
+ uv run --locked --no-dev --group docs zensical build --clean --strict --config-file zensical.pt-br.toml
53
+ ```
@@ -0,0 +1,65 @@
1
+ [project]
2
+ name = "fastapi-ratelimits"
3
+ version = "0.1.0"
4
+ description = "Async rate limiting for FastAPI dependencies, powered by limits"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "fastapi>=0.163.1,<1",
11
+ "limits>=5.8,<6",
12
+ ]
13
+
14
+ [[project.authors]]
15
+ name = "Bernardo Gomes"
16
+
17
+ [project.urls]
18
+ Repository = "https://github.com/Bernardoow/fastapi-ratelimits"
19
+ Issues = "https://github.com/Bernardoow/fastapi-ratelimits/issues"
20
+
21
+ [project.optional-dependencies]
22
+ redis = ["redis>=5.2,<8"]
23
+
24
+ [dependency-groups]
25
+ dev = [
26
+ "asgi-lifespan>=2.1,<3",
27
+ "httpx>=0.27,<1",
28
+ "mypy>=1.15,<2",
29
+ "pytest>=8,<10",
30
+ "pytest-asyncio>=0.24,<2",
31
+ "ruff>=0.11,<1",
32
+ ]
33
+ docs = [
34
+ "mkdocstrings[python]>=1.0.6,<2",
35
+ "zensical>=0.1.1,<0.2",
36
+ ]
37
+
38
+ [tool.pytest.ini_options]
39
+ asyncio_mode = "auto"
40
+ asyncio_default_fixture_loop_scope = "function"
41
+ testpaths = ["tests"]
42
+ markers = ["redis: integration tests requiring a disposable Redis server"]
43
+
44
+ [tool.mypy]
45
+ python_version = "3.11"
46
+ strict = true
47
+ files = ["src"]
48
+
49
+ [tool.ruff]
50
+ target-version = "py311"
51
+ line-length = 99
52
+
53
+ [tool.ruff.lint]
54
+ select = [
55
+ "E",
56
+ "F",
57
+ "I",
58
+ "UP",
59
+ "B",
60
+ ]
61
+ ignore = ["B008"]
62
+
63
+ [build-system]
64
+ requires = ["uv_build>=0.12.17,<0.13.0"]
65
+ build-backend = "uv_build"
@@ -0,0 +1,56 @@
1
+ [project]
2
+ name = "fastapi-ratelimits"
3
+ version = "0.1.0"
4
+ description = "Async rate limiting for FastAPI dependencies, powered by limits"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "Bernardo Gomes" }
10
+ ]
11
+ requires-python = ">=3.11"
12
+ dependencies = ["fastapi>=0.163.1,<1", "limits>=5.8,<6"]
13
+
14
+ [project.urls]
15
+ Repository = "https://github.com/Bernardoow/fastapi-ratelimits"
16
+ Issues = "https://github.com/Bernardoow/fastapi-ratelimits/issues"
17
+
18
+ [project.optional-dependencies]
19
+ redis = ["redis>=5.2,<8"]
20
+
21
+ [dependency-groups]
22
+ dev = [
23
+ "asgi-lifespan>=2.1,<3",
24
+ "httpx>=0.27,<1",
25
+ "mypy>=1.15,<2",
26
+ "pytest>=8,<10",
27
+ "pytest-asyncio>=0.24,<2",
28
+ "ruff>=0.11,<1",
29
+ ]
30
+ docs = [
31
+ "mkdocstrings[python]>=1.0.6,<2",
32
+ "zensical>=0.1.1,<0.2",
33
+ ]
34
+
35
+ [tool.pytest.ini_options]
36
+ asyncio_mode = "auto"
37
+ asyncio_default_fixture_loop_scope = "function"
38
+ testpaths = ["tests"]
39
+ markers = ["redis: integration tests requiring a disposable Redis server"]
40
+
41
+ [tool.mypy]
42
+ python_version = "3.11"
43
+ strict = true
44
+ files = ["src"]
45
+
46
+ [tool.ruff]
47
+ target-version = "py311"
48
+ line-length = 99
49
+
50
+ [tool.ruff.lint]
51
+ select = ["E", "F", "I", "UP", "B"]
52
+ ignore = ["B008"]
53
+
54
+ [build-system]
55
+ requires = ["uv_build>=0.12.17,<0.13.0"]
56
+ build-backend = "uv_build"
@@ -0,0 +1,24 @@
1
+ from .callbacks import SynchronousCallbackWarning
2
+ from .defaults import default_route_id, key_by_ip
3
+ from .exceptions import (
4
+ RateLimitExceeded,
5
+ StorageUnavailable,
6
+ rate_limit_exceeded_handler,
7
+ storage_unavailable_handler,
8
+ )
9
+ from .headers import RateLimitHeadersMiddleware, RateLimitSnapshot, default_rate_limit_headers
10
+ from .limiter import Limiter
11
+
12
+ __all__ = [
13
+ "Limiter",
14
+ "RateLimitExceeded",
15
+ "RateLimitHeadersMiddleware",
16
+ "RateLimitSnapshot",
17
+ "StorageUnavailable",
18
+ "SynchronousCallbackWarning",
19
+ "default_rate_limit_headers",
20
+ "default_route_id",
21
+ "key_by_ip",
22
+ "rate_limit_exceeded_handler",
23
+ "storage_unavailable_handler",
24
+ ]
@@ -0,0 +1,30 @@
1
+ import functools
2
+ import inspect
3
+ import warnings
4
+ from collections.abc import Callable
5
+ from typing import Any
6
+
7
+
8
+ class SynchronousCallbackWarning(UserWarning):
9
+ """A configured callback uses a worker thread instead of native async I/O."""
10
+
11
+
12
+ def is_async_callable(callback: Callable[..., Any]) -> bool:
13
+ while isinstance(callback, functools.partial):
14
+ callback = callback.func
15
+ return inspect.iscoroutinefunction(callback) or inspect.iscoroutinefunction(
16
+ type(callback).__call__
17
+ )
18
+
19
+
20
+ def warn_if_sync(callback: Callable[..., Any]) -> None:
21
+ if not (
22
+ is_async_callable(callback)
23
+ or inspect.isasyncgenfunction(callback)
24
+ or inspect.isasyncgenfunction(type(callback).__call__)
25
+ ):
26
+ warnings.warn(
27
+ "A synchronous callback runs in a worker thread. Prefer async def with async I/O.",
28
+ SynchronousCallbackWarning,
29
+ stacklevel=3,
30
+ )
@@ -0,0 +1,19 @@
1
+ from fastapi import Request
2
+ from fastapi.routing import APIRoute
3
+
4
+
5
+ async def key_by_ip(request: Request) -> str:
6
+ if request.client is None:
7
+ raise ValueError("The request has no client address; configure a key_func")
8
+ return request.client.host
9
+
10
+
11
+ async def default_route_id(request: Request) -> str:
12
+ route = request.scope.get("route")
13
+ # FastAPI >=0.163 keeps include-specific IDs in an effective route context.
14
+ context = request.scope.get("fastapi", {}).get("effective_route_context")
15
+ if context is not None and context.original_route is route:
16
+ return str(context.operation_id or context.unique_id)
17
+ if isinstance(route, APIRoute):
18
+ return route.operation_id or route.unique_id
19
+ raise ValueError("Rate limiting requires a FastAPI HTTP route")
@@ -0,0 +1,37 @@
1
+ import math
2
+ import time
3
+
4
+ from fastapi import HTTPException, Request
5
+ from fastapi.exception_handlers import http_exception_handler
6
+ from limits import RateLimitItem
7
+ from starlette.responses import Response
8
+
9
+
10
+ class RateLimitExceeded(HTTPException):
11
+ def __init__(self, *, limit: RateLimitItem, reset_at: float, cost: int, scope: str) -> None:
12
+ self.limit = limit
13
+ self.reset_at = reset_at
14
+ self.cost = cost
15
+ self.scope = scope
16
+ super().__init__(
17
+ status_code=429,
18
+ detail="Rate limit exceeded",
19
+ headers={"Retry-After": str(max(1, math.ceil(reset_at - time.time())))},
20
+ )
21
+
22
+
23
+ async def rate_limit_exceeded_handler(request: Request, exc: Exception) -> Response:
24
+ if not isinstance(exc, RateLimitExceeded):
25
+ raise exc
26
+ return await http_exception_handler(request, exc)
27
+
28
+
29
+ class StorageUnavailable(HTTPException):
30
+ def __init__(self) -> None:
31
+ super().__init__(status_code=503, detail="Rate limit storage unavailable")
32
+
33
+
34
+ async def storage_unavailable_handler(request: Request, exc: Exception) -> Response:
35
+ if not isinstance(exc, StorageUnavailable):
36
+ raise exc
37
+ return await http_exception_handler(request, exc)
@@ -0,0 +1,84 @@
1
+ import inspect
2
+ import math
3
+ from collections.abc import Awaitable, Callable, Mapping
4
+ from dataclasses import dataclass
5
+
6
+ from starlette.concurrency import run_in_threadpool
7
+ from starlette.datastructures import MutableHeaders
8
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
9
+
10
+ from .callbacks import is_async_callable, warn_if_sync
11
+
12
+ _SNAPSHOTS = "fastapi_ratelimits.snapshots"
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class RateLimitSnapshot:
17
+ """The quota observed immediately after an admitted rule consumed its cost."""
18
+
19
+ limit: int
20
+ remaining: int
21
+ reset_at: float
22
+ cost: int
23
+ scope: str
24
+ shared: bool
25
+
26
+
27
+ HeadersFactory = Callable[
28
+ [tuple[RateLimitSnapshot, ...]], Mapping[str, str] | Awaitable[Mapping[str, str]]
29
+ ]
30
+
31
+
32
+ async def default_rate_limit_headers(
33
+ snapshots: tuple[RateLimitSnapshot, ...],
34
+ ) -> Mapping[str, str]:
35
+ if not snapshots:
36
+ return {}
37
+ rule = min(snapshots, key=lambda item: item.remaining / item.limit)
38
+ return {
39
+ "X-RateLimit-Limit": str(rule.limit),
40
+ "X-RateLimit-Remaining": str(rule.remaining),
41
+ "X-RateLimit-Reset": str(math.ceil(rule.reset_at)),
42
+ }
43
+
44
+
45
+ def request_snapshots(*, scope: Scope) -> list[RateLimitSnapshot] | None:
46
+ snapshots: list[RateLimitSnapshot] | None = scope.get(_SNAPSHOTS)
47
+ return snapshots
48
+
49
+
50
+ class RateLimitHeadersMiddleware:
51
+ """Add quota headers to final HTTP responses, including streaming responses."""
52
+
53
+ def __init__(
54
+ self, app: ASGIApp, *, headers_func: HeadersFactory = default_rate_limit_headers
55
+ ) -> None:
56
+ warn_if_sync(headers_func)
57
+ self._app = app
58
+ self._headers_func = headers_func
59
+ self._async_headers = is_async_callable(headers_func)
60
+
61
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
62
+ if scope["type"] != "http":
63
+ await self._app(scope, receive, send)
64
+ return
65
+
66
+ snapshots: list[RateLimitSnapshot] = []
67
+ scope[_SNAPSHOTS] = snapshots
68
+
69
+ async def send_with_headers(message: Message) -> None:
70
+ if message["type"] == "http.response.start" and message["status"] < 400 and snapshots:
71
+ values = tuple(snapshots)
72
+ headers = (
73
+ self._headers_func(values)
74
+ if self._async_headers
75
+ else await run_in_threadpool(self._headers_func, values)
76
+ )
77
+ if inspect.isawaitable(headers):
78
+ headers = await headers
79
+ response_headers = MutableHeaders(scope=message)
80
+ for name, value in headers.items():
81
+ response_headers[name] = value
82
+ await send(message)
83
+
84
+ await self._app(scope, receive, send_with_headers)
@@ -0,0 +1,191 @@
1
+ from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterator, Mapping
2
+ from contextlib import AsyncExitStack, asynccontextmanager
3
+ from typing import Any, TypeVar
4
+ from urllib.parse import quote
5
+
6
+ from fastapi import Depends, FastAPI, Request
7
+ from limits import RateLimitItem, parse_many
8
+ from limits.aio.storage import Storage
9
+ from limits.aio.strategies import STRATEGIES, RateLimiter
10
+ from limits.errors import StorageError
11
+
12
+ from .callbacks import warn_if_sync
13
+ from .defaults import default_route_id, key_by_ip
14
+ from .exceptions import RateLimitExceeded, StorageUnavailable
15
+ from .headers import RateLimitSnapshot, request_snapshots
16
+ from .storage import open_storage
17
+
18
+ T = TypeVar("T")
19
+ ValueProvider = Callable[..., T | Awaitable[T] | Iterator[T] | AsyncIterator[T]]
20
+ _STRATEGIES: Mapping[str, Callable[[Storage], RateLimiter]] = STRATEGIES
21
+ _STRATEGY_METHODS = {
22
+ "moving-window": ("acquire_entry", "get_moving_window"),
23
+ "sliding-window-counter": ("acquire_sliding_window_entry", "get_sliding_window"),
24
+ }
25
+
26
+
27
+ def _resolve_through_fastapi(source: T | ValueProvider[T]) -> ValueProvider[T]:
28
+ if callable(source):
29
+ return source
30
+
31
+ async def constant() -> T:
32
+ return source
33
+
34
+ return constant
35
+
36
+
37
+ def _parse_rule(value: str) -> RateLimitItem:
38
+ if not isinstance(value, str):
39
+ raise ValueError("A limit must be a rate limit string")
40
+ items = parse_many(value)
41
+ if len(items) != 1 or items[0].amount <= 0 or items[0].multiples <= 0:
42
+ raise ValueError("Provide one rate limit with a positive amount and window per rule")
43
+ return items[0]
44
+
45
+
46
+ def _validate_cost(cost: int) -> None:
47
+ if isinstance(cost, bool) or not isinstance(cost, int) or cost < 1:
48
+ raise ValueError("cost must be a positive integer")
49
+
50
+
51
+ class Limiter:
52
+ """Configure an asynchronous quota strategy and create FastAPI dependencies."""
53
+
54
+ def __init__(
55
+ self,
56
+ *,
57
+ storage_uri: str | None = None,
58
+ storage: Storage | None = None,
59
+ storage_options: Mapping[str, Any] | None = None,
60
+ strategy: str = "fixed-window",
61
+ key_func: ValueProvider[str] = key_by_ip,
62
+ route_id_func: ValueProvider[str] = default_route_id,
63
+ ) -> None:
64
+ if (storage_uri is None) == (storage is None):
65
+ raise ValueError("Configure exactly one of storage_uri or storage")
66
+ if storage_uri is not None and not storage_uri.startswith("async+"):
67
+ raise ValueError("storage_uri must select an async+ storage")
68
+ if storage is not None and not isinstance(storage, Storage):
69
+ raise TypeError("storage must be an asynchronous limits storage")
70
+ if storage is not None and storage_options is not None:
71
+ raise ValueError("Configure storage_options only with storage_uri")
72
+ if strategy not in _STRATEGIES:
73
+ raise ValueError(f"Unknown rate limit strategy: {strategy!r}")
74
+ self._storage_uri = storage_uri
75
+ self._storage = storage
76
+ self._storage_options = dict(storage_options or {})
77
+ self._strategy_name = strategy
78
+ warn_if_sync(key_func)
79
+ warn_if_sync(route_id_func)
80
+ self._key_func = key_func
81
+ self._route_id_func = route_id_func
82
+ self._active: dict[FastAPI, RateLimiter] = {}
83
+
84
+ @asynccontextmanager
85
+ async def lifespan(self, app: FastAPI) -> AsyncIterator[None]:
86
+ """Start the limiter for an application and release any resources it owns."""
87
+ if app in self._active:
88
+ raise RuntimeError("Limiter.lifespan is already active for this application")
89
+ async with AsyncExitStack() as stack:
90
+ storage = self._storage
91
+ if storage is None:
92
+ assert self._storage_uri is not None
93
+ storage = await stack.enter_async_context(
94
+ open_storage(uri=self._storage_uri, options=self._storage_options)
95
+ )
96
+ if any(
97
+ not callable(getattr(storage, method, None))
98
+ for method in _STRATEGY_METHODS.get(self._strategy_name, ())
99
+ ):
100
+ raise ValueError(
101
+ f"{type(storage).__name__} does not support the {self._strategy_name} strategy"
102
+ )
103
+ self._active[app] = _STRATEGIES[self._strategy_name](storage)
104
+ try:
105
+ yield
106
+ finally:
107
+ del self._active[app]
108
+
109
+ def limit(
110
+ self,
111
+ value: str | ValueProvider[str],
112
+ *,
113
+ key_func: ValueProvider[str] | None = None,
114
+ group: str | None = None,
115
+ cost: int | ValueProvider[int] = 1,
116
+ ) -> Callable[..., Coroutine[Any, Any, None]]:
117
+ """Build one rule for Depends, scoped to the route or an explicit group."""
118
+ static_item = None if callable(value) else _parse_rule(value)
119
+ if not callable(cost):
120
+ _validate_cost(cost)
121
+ if group is not None and (not isinstance(group, str) or not group):
122
+ raise ValueError("group must be a nonempty string")
123
+
124
+ for provider in (key_func, value, cost):
125
+ if callable(provider):
126
+ warn_if_sync(provider)
127
+ key_dependency = self._key_func if key_func is None else key_func
128
+ scope_dependency = (
129
+ self._route_id_func if group is None else _resolve_through_fastapi(group)
130
+ )
131
+ value_dependency: ValueProvider[str] = _resolve_through_fastapi(value)
132
+ cost_dependency: ValueProvider[int] = _resolve_through_fastapi(cost)
133
+ scope_type = "route" if group is None else "group"
134
+
135
+ async def check(
136
+ request: Request,
137
+ *,
138
+ key: str = Depends(key_dependency),
139
+ scope: str = Depends(scope_dependency),
140
+ resolved_limit: str = Depends(value_dependency),
141
+ resolved_cost: int = Depends(cost_dependency),
142
+ ) -> None:
143
+ if not isinstance(key, str) or not key:
144
+ raise ValueError("key_func must return a nonempty string")
145
+ if not isinstance(scope, str) or not scope:
146
+ raise ValueError("route_id_func must return a nonempty string")
147
+ item = static_item if static_item is not None else _parse_rule(resolved_limit)
148
+ _validate_cost(resolved_cost)
149
+ identifiers = (
150
+ self._strategy_name,
151
+ scope_type,
152
+ quote(scope, safe=""),
153
+ quote(key, safe=""),
154
+ )
155
+ strategy = self._active.get(request.app)
156
+ if strategy is None:
157
+ raise RuntimeError("Use Limiter.lifespan before serving requests")
158
+ backend_errors = strategy.storage.base_exceptions
159
+ if isinstance(backend_errors, type):
160
+ backend_errors = (backend_errors,)
161
+ failures: tuple[type[Exception], ...] = (
162
+ StorageError,
163
+ TimeoutError,
164
+ ConnectionError,
165
+ *backend_errors,
166
+ )
167
+ snapshots = request_snapshots(scope=request.scope)
168
+ try:
169
+ admitted = await strategy.hit(item, *identifiers, cost=resolved_cost)
170
+ if admitted and snapshots is None:
171
+ return
172
+ stats = await strategy.get_window_stats(item, *identifiers)
173
+ except failures as exc:
174
+ raise StorageUnavailable() from exc
175
+ if not admitted:
176
+ raise RateLimitExceeded(
177
+ limit=item, reset_at=stats.reset_time, cost=resolved_cost, scope=scope
178
+ )
179
+ if snapshots is not None:
180
+ snapshots.append(
181
+ RateLimitSnapshot(
182
+ limit=item.amount,
183
+ remaining=stats.remaining,
184
+ reset_at=stats.reset_time,
185
+ cost=resolved_cost,
186
+ scope=scope,
187
+ shared=group is not None,
188
+ )
189
+ )
190
+
191
+ return check
@@ -0,0 +1,46 @@
1
+ import asyncio
2
+ from collections.abc import AsyncIterator, Mapping
3
+ from contextlib import asynccontextmanager
4
+ from typing import Any, Protocol, cast
5
+
6
+ from limits.aio.storage import MemoryStorage, RedisStorage, Storage
7
+ from limits.aio.storage.redis.redispy import RedispyBridge
8
+
9
+ _REDIS_SCHEMES = {"async+redis", "async+rediss", "async+redis+unix"}
10
+
11
+
12
+ class _RedisConnection(Protocol):
13
+ async def aclose(self, *, close_connection_pool: bool) -> None: ...
14
+
15
+
16
+ @asynccontextmanager
17
+ async def open_storage(*, uri: str, options: Mapping[str, Any]) -> AsyncIterator[Storage]:
18
+ scheme, separator, _ = uri.partition("://")
19
+ if not separator:
20
+ raise ValueError("storage_uri must be an async storage URI")
21
+
22
+ if scheme == "async+memory":
23
+ if options:
24
+ raise ValueError("Memory storage does not take storage_options")
25
+ memory = MemoryStorage()
26
+ try:
27
+ yield memory
28
+ finally:
29
+ if memory.timer is not None:
30
+ memory.timer.cancel()
31
+ await asyncio.gather(memory.timer, return_exceptions=True)
32
+ return
33
+
34
+ if scheme not in _REDIS_SCHEMES:
35
+ raise ValueError("Use an async memory or Redis URI, or provide an async storage object")
36
+
37
+ settings = dict(options)
38
+ if settings.pop("implementation", "redispy") != "redispy" or "connection_pool" in settings:
39
+ raise ValueError("Redis URI configuration uses a Redis-py client owned by the limiter")
40
+ redis = RedisStorage(uri, implementation="redispy", **settings)
41
+ try:
42
+ yield redis
43
+ finally:
44
+ # limits has no backend-independent close method. This connection is owned here.
45
+ connection = cast(RedispyBridge, redis.bridge).get_connection()
46
+ await cast(_RedisConnection, connection).aclose(close_connection_pool=True)