- 有个接口内容信息比较敏感,遂设置限流操作
通常的限流操作就包括对某个用户或者某个IP进行限流,每分钟或者每天最多能访问多少次之类的等等。 - FaslApi中的限流操作开源库SlowApi https://github.com/laurentS/slowapi
这个库是根据flask-limiter改编而来,应该也是在FastApi中使用人数最多的一个库,但是感觉网上的资料比较少,我仔细看了一下,这个库本身所支持的功能也比较单一,很多个性化的操作还是需要自己来写。
比如想根据用户类型来进行限流操作分级,官方没有提供支持,这个issue里个老哥实现了。https://github.com/laurentS/slowapi/issues/13
还有一个问题是虽然默认支持内存计数,但是FastApi开多个workers跑时每个进程都会有自己独立的limit。想实现总体上的限流要加入redis作为backend。 - SlowApi的简单用法
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from fastapi import FastAPI
from starlette.requests import Request
from setting import config, env
from extensions import logger
def get_real_remote_address(request: Request) -> str:
"""
Returns the ip address for the current request (or 127.0.0.1 if none found)
"""
real_ip = request.client.host
if request and request.headers<