首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >所有“路径/*”下的FastAPI和SlowAPI限制请求

所有“路径/*”下的FastAPI和SlowAPI限制请求
EN

Stack Overflow用户
提问于 2022-02-18 21:40:01
回答 1查看 1.1K关注 0票数 2

我和SlowAPI有个问题。所有请求都根据中间件受到限制,但我无法共同限制路径/schools/下的所有请求。

我的代码:

代码语言:javascript
运行
复制
from fastapi import FastAPI, Request, Response, status
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware

limiter = Limiter(key_func=get_remote_address, default_limits=["2/5seconds"])
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

origins = ["http://127.0.0.1/", "http://localhost", "http://192.168.1.75"] ## CORS

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(SlowAPIMiddleware) ## Rate-limit all request

@app.get('/schools/{regione}/{provincia}/{comune}')
def search_school(request: Request, response: Response, regione: str, provincia: str, comune: str):
        return {"message": 'No schools found!', "status": 'error', "code": 200} ## Or if found return schools informations

@app.get('/testpath/{regione}') ## Works with one path. If I add "provincia" and "comune" non work
def search_school(request: Request, response: Response, regione: str, provincia: str, comune: str):
        return {"message": 'No schools found!', "status": 'error', "code": 200} ## Or if found return schools informations

当我用/schools/{region}/{province}/{city}向jQuery发送请求时,整个url是有限的,因此,如果我更改区域或省,则会重置限制。如何使自己为/schools/*应用设置

示例:

每5秒2次请求

如果我向apiURL+/schools/Lombardy/Milan/Milan发送请求,则限制会增加1,如果我在第三次发出指定的2请求,则会被阻塞。

但是,如果我没有将其更改为相同的域,而是更改了城市(apiURL+/schools/Sicily/Palermo/Palermo),则限制重置并返回到1。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71180148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档