-
Notifications
You must be signed in to change notification settings - Fork 0
/
starlette.py
48 lines (40 loc) · 1.37 KB
/
starlette.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from limits.aio.storage import MemoryStorage
from limits.aio.strategies import MovingWindowRateLimiter
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import PlainTextResponse
from starlette.routing import Route
import fourtwonine
from fourtwonine import RateLimitConfig, RateLimitMiddleware
async def rate_limited_endpoint(_request: Request):
return PlainTextResponse("hit me 11 times in a minute!")
async def hello(_request: Request):
return PlainTextResponse("hello world!")
app = Starlette(
# Apply a global rate limit...
middleware=[
Middleware(RateLimitMiddleware, limit_value="20/minute", bucket="global"),
],
routes=[
Route(
"/rate-limited",
rate_limited_endpoint,
# ...and then a specific rate limit for an endpoint.
middleware=[
Middleware(
RateLimitMiddleware, limit_value="10/minute", bucket="rate-limited"
),
],
),
Route("/hello", hello),
],
)
# Attach a global configuration to the app, which will be used for
# all middlewares that don't specify their own configuration.
fourtwonine.initialize_config(
app,
RateLimitConfig(
limiter=MovingWindowRateLimiter(MemoryStorage()),
),
)