try to add rate limiting with FastAPI_Limiter
Build and publish bnuy api / build (push) Successful in 13m10s
Build and publish bnuy api / build (push) Successful in 13m10s
This commit is contained in:
@@ -19,5 +19,13 @@ services:
|
||||
- MARIADB_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- mariadb_data:/var/lib/mysql
|
||||
|
||||
redis:
|
||||
image: valkey:9
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
|
||||
volumes:
|
||||
mariadb_data:
|
||||
redis_data:
|
||||
@@ -19,5 +19,13 @@ services:
|
||||
- MARIADB_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- mariadb_data:/var/lib/mysql
|
||||
|
||||
redis:
|
||||
image: valkey:9
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
|
||||
volumes:
|
||||
mariadb_data:
|
||||
redis_data:
|
||||
@@ -1,6 +1,10 @@
|
||||
import aiohttp
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi_limiter import FastAPILimiter
|
||||
from fastapi_limiter.depends import RateLimiter
|
||||
import redis.asyncio as redis
|
||||
from fastapi import Depends
|
||||
import asyncmy
|
||||
import asyncio
|
||||
import os
|
||||
@@ -39,6 +43,8 @@ async def connect_db(app: FastAPI):
|
||||
maxsize=20
|
||||
)
|
||||
await create_tables(app.state.pool)
|
||||
redis_client = await redis.from_url("redis://localhost")
|
||||
await FastAPILimiter.init(redis_client)
|
||||
task = asyncio.create_task(fetch_images())
|
||||
try:
|
||||
yield
|
||||
@@ -50,6 +56,8 @@ async def connect_db(app: FastAPI):
|
||||
pass
|
||||
app.state.pool.close()
|
||||
await app.state.pool.wait_closed()
|
||||
await FastAPILimiter.close()
|
||||
await redis_client.close()
|
||||
|
||||
app = FastAPI(lifespan=connect_db)
|
||||
|
||||
@@ -71,7 +79,7 @@ async def create_tables(pool):
|
||||
async def root():
|
||||
return {"message": "yes the api works, maybe i will create a small landing page later here"}
|
||||
|
||||
@app.get("/random")
|
||||
@app.get("/random", dependencies=[Depends(RateLimiter(times=25, seconds=60))])
|
||||
async def get_random_bnuy(request: Request):
|
||||
async with app.state.pool.acquire() as conn:
|
||||
async with conn.cursor() as cursor:
|
||||
@@ -86,7 +94,7 @@ async def get_random_bnuy(request: Request):
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="No available images found")
|
||||
|
||||
@app.get("/images/{filename}")
|
||||
@app.get("/images/{filename}", dependencies=[Depends(RateLimiter(times=25, seconds=60))])
|
||||
async def get_image(filename: str):
|
||||
async with app.state.pool.acquire() as conn:
|
||||
async with conn.cursor() as cursor:
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
fastapi[standard]
|
||||
fastapi_limiter
|
||||
asyncmy
|
||||
aiohttp
|
||||
redis
|
||||
Reference in New Issue
Block a user