我有問題。當我正確地從瀏覽器或郵遞員發出太多請求時,API (slowapi) 會阻止我,因為我已正確設定,但如果我通過 AJAX 和 jquery 的 $ .getJSON 發出請求,API 不會阻止我。我該如何解決?我的代碼(從完整代碼中提取):
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)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(SlowAPIMiddleware)
@app.get('/schools/{regione}/{provincia}/{comune}')
def search_school(request: Request, response: Response, regione: str, provincia: str, comune: str):
if(request.headers.get("Provider") == "Test-User-Provider"):
return {"message": "OK", "status": "success", "code": 200}
else:
response.status_code = status.HTTP_400_BAD_REQUEST
return {"message": "Provider not found", "status": "error", "code": 400}
瀏覽器結果(作業):
{"error":"Rate limit exceeded: 2 per 5 second"}
jQuery代碼(不作業):
$.getJSON(apiURL "/schools/Test/Test/Test", function(data) {
console.log(data)
});
顯然,使用 jquery,我嘗試每秒發出很多請求控制臺瀏覽器結果(不限于!):
{message: '...', status: 'success', code: 200}

萬分感謝。
更新
通過 jquery 我嘗試向其他路徑發出請求,并且它是正確的速率限制。如果我向此路徑發出請求,/schools/{region}/{province}/{municipality}則速率限制不起作用
更新 2
I refer the updated and tested code. When I send a request to path /testpath /{region} it is correctly rate-limited. If instead I send a request to some sub-paths (/schools/{region}/{province}/{municipality} it is not rate-limited.
The jQuery code is the same as listed above
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
If i use schools path:

If i use testpath it's correct rate-limited:

uj5u.com熱心網友回復:
測驗您的代碼并且作業正常,只要您在方法”中用直雙引號替換結束雙引號:"getJSON()
$.getJSON(apiURL "/security/validate_token", function(data) {
console.log(data)
});
您在上面寫了“狀態回應是個性化的,我自己決定”。因此,如果您仍然收到{message: '...', status: 'success', code: 200}回復,我建議您嘗試回傳一條簡單的訊息,例如 ,return {"status": "success"}并查看它是否按預期作業。如果不是,則可能是您的自定義回應中沒有以正確的方式實施。
更新
以下應該按預期作業。如果不是,那么問題可能出在您的問題中未包含的代碼中的其他地方。我還建議將它作為模板添加到您的應用程式中,因為從您發布的錯誤來看,您似乎收到了Cross-Origin警告。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" >
function on_click(){
$.getJSON("http://127.0.0.1:8000/schools/Test/Test/Test", function(data) {
console.log(data)
});
}
</script>
</head>
<body>
<input type="button" value="submit" onclick="on_click()">
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427844.html
標籤:python jquery xmlhttprequest fastapi slowapi
