You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
887 B
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
from flask import request
from flask_limiter import Limiter
from iti.applications.common.utils import fail
def get_user_identifier():
"""
获取用户标识符
如果用户已登录则返回用户ID
如果用户未登录则返回请求的IP地址
"""
verify_jwt_in_request(optional=True, verify_type=False)
identity = get_jwt_identity()
if identity is not None:
return identity
return request.remote_addr
# 全局 limiter 实例
limiter = Limiter(key_func=get_user_identifier)
def init_limiter(app) -> None:
"""
初始化限流器
从 Flask 配置中读取限流设置
"""
limiter.init_app(app)
@app.errorhandler(429)
def handle_rate_limit_exceeded(e):
return fail(message="请求过于频繁,请稍后再试", code=429)