mirror of
https://github.com/fastapi-practices/fastapi-best-architecture.git
synced 2026-09-21 21:15:13 +00:00
Add apis rate limiter (#72)
* Add apis rate limiter * update the limiter storage prefix
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from fastapi_limiter.depends import RateLimiter
|
||||
|
||||
from backend.app.common.jwt import DependsUser, get_token, jwt_decode, CurrentJwtAuth
|
||||
from backend.app.common.response.response_schema import response_base
|
||||
@@ -18,7 +19,12 @@ async def swagger_user_login(form_data: OAuth2PasswordRequestForm = Depends()) -
|
||||
return SwaggerToken(access_token=token, user=user)
|
||||
|
||||
|
||||
@router.post('/login', summary='用户登录', description='json 格式登录, 仅支持在第三方api工具调试接口, 例如: postman')
|
||||
@router.post(
|
||||
'/login',
|
||||
summary='用户登录',
|
||||
description='json 格式登录, 仅支持在第三方api工具调试接口, 例如: postman',
|
||||
dependencies=[Depends(RateLimiter(times=5, minutes=15))],
|
||||
)
|
||||
async def user_login(obj: Auth):
|
||||
access_token, refresh_token, access_expire, refresh_expire, user = await UserService.login(obj)
|
||||
data = LoginToken(
|
||||
|
||||
@@ -13,7 +13,6 @@ from backend.app.models.sys_casbin_rule import CasbinRule
|
||||
|
||||
|
||||
class RBAC:
|
||||
|
||||
@staticmethod
|
||||
async def get_casbin_enforcer() -> casbin.Enforcer:
|
||||
"""
|
||||
|
||||
@@ -5,6 +5,7 @@ from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi_limiter import FastAPILimiter
|
||||
from fastapi_pagination import add_pagination
|
||||
|
||||
from backend.app.api.routers import v1
|
||||
@@ -27,15 +28,19 @@ async def register_init(app: FastAPI):
|
||||
"""
|
||||
# 创建数据库表
|
||||
await create_table()
|
||||
# 连接redis
|
||||
# 连接 redis
|
||||
await redis_client.open()
|
||||
# 初始化 limiter
|
||||
await FastAPILimiter.init(redis_client, prefix='fba_limiter')
|
||||
# 启动定时任务
|
||||
scheduler.start()
|
||||
|
||||
yield
|
||||
|
||||
# 关闭redis连接
|
||||
# 关闭 redis 连接
|
||||
await redis_client.close()
|
||||
# 关闭 limiter
|
||||
await FastAPILimiter.close()
|
||||
# 关闭定时任务
|
||||
scheduler.shutdown()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user