Skip to content

Commit

Permalink
Merge pull request #48 from tkrtmy/deprecated-on_event
Browse files Browse the repository at this point in the history
use lifespan
  • Loading branch information
long2ice authored Jan 5, 2024
2 parents 9379802 + 260affd commit 7851554
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 16 deletions.
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,20 @@ request per `5` seconds in route `/`.
```py
import redis.asyncio as redis
import uvicorn
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI

from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter

app = FastAPI()


@app.on_event("startup")
async def startup():
redis_connection = redis.from_url("redis://localhost", encoding="utf-8", decode_responses=True)
@asynccontextmanager
async def lifespan(_: FastAPI):
redis_connection = redis.from_url("redis://localhost:6379", encoding="utf8")
await FastAPILimiter.init(redis_connection)
yield
await FastAPILimiter.close()

app = FastAPI(lifespan=lifespan)

@app.get("/", dependencies=[Depends(RateLimiter(times=2, seconds=5))])
async def index():
Expand Down
18 changes: 8 additions & 10 deletions examples/main.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import redis.asyncio as redis
import uvicorn
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI, HTTPException, WebSocket

from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter, WebSocketRateLimiter

app = FastAPI()


@app.on_event("startup")
async def startup():
r = redis.from_url("redis://localhost", encoding="utf8")
await FastAPILimiter.init(r)
@asynccontextmanager
async def lifespan(_: FastAPI):
redis_connection = redis.from_url("redis://localhost:6379", encoding="utf8")
await FastAPILimiter.init(redis_connection)
yield
await FastAPILimiter.close()


@app.on_event("shutdown")
async def shutdown():
await FastAPILimiter.close()
app = FastAPI(lifespan=lifespan)


@app.get("/", dependencies=[Depends(RateLimiter(times=2, seconds=5))])
Expand Down

0 comments on commit 7851554

Please sign in to comment.