使用flask_limiter, app启动时有个告警:
flask_limiter/extension.py:336: UserWarning: Using the in-memory storage for tracking rate limits as no storage was explicitly specified. This is not recommended for production use. See: https://flask-limiter.readthedocs.io#configuring-a-storage-backend for documentation about configuring the storage backend.
有个介绍:
Flask-Limiter provides rate limiting features to flask routes. It has support for a configurable backend for storage with current implementations for in-memory, redis and memcache.
频率限制的依据缓存数据,可以存在内存,redis,或者memcache上。生产环境不推荐 in-memory storage。
改用redis吧:
uri = "redis://name:passwd@192.168.111.111:6379/3"
limiter = Limiter(key_func=get_remote_address, default_limits=["1 per hour"],
storage_uri=uri)
另外,类似mysql, 如果redis密码带@, uri可以考虑用如下方法:
from urllib.parse import quote_plus
host = "xxx"
port = "xxx"
db = "xxx"
user = "xxx"
pwd = quote_plus("xxx@xxx")
uri = f"redis://{user}:{pwd}@{host}:{port}/{db}"
但在启动app时会有报错:
│ /usr/python38/lib/python3.8/site-packages/flask_limiter/extension.py:345 in init_app │
│ │
│ 342 │ │ │ storage_uri_from_config = "memory://" │
│ 343 │ │ self._storage = cast( │
│ 344 │ │ │ Storage, │
│ ❱ 345 │ │ │ storage_from_string( │
│ 346 │ │ │ │ self._storage_uri or storage_uri_from_config, **self._storage_options │
│ 347 │ │ │ ), │
│ 348 │ │ ) │
│ │
│ /usr/python38/lib/python3.8/site-packages/limits/storage/__init__.py:63 in storage_from_string │
│ │
│ 60 │ │
│ 61 │ if scheme not in SCHEMES: │
│ 62 │ │ raise ConfigurationError("unknown storage scheme : %s" % storage_string) │
│ ❱ 63 │ return cast(StorageTypes, SCHEMES[scheme](storage_string, **options)) │
│ 64 │
│ 65 │
│ 66 __all__ = [ │
│ │
│ /usr/python38/lib/python3.8/site-packages/limits/storage/redis.py:152 in __init__ │
│ │
│ 149 │ │ :raise ConfigurationError: when the :pypi:`redis` library is not available │
│ 150 │ │ """ │
│ 151 │ │ super().__init__(uri, **options) │
│ ❱ 152 │ │ redis = self.dependencies["redis"].module │
│ 153 │ │ │
│ 154 │ │ uri = uri.replace("redis+unix", "unix") │
│ 155 │
│ │
│ /usr/python38/lib/python3.8/site-packages/limits/util.py:68 in __getitem__ │
│ │
│ 65 │ │ dependency = super().__getitem__(key) │
│ 66 │ │ │
│ 67 │ │ if dependency == DependencyDict.Missing: │
│ ❱ 68 │ │ │ raise ConfigurationError(f"{key} prerequisite not available") │
│ 69 │ │ elif dependency.version_required and ( │
│ 70 │ │ │ not dependency.version_found │
│ 71 │ │ │ or dependency.version_found < dependency.version_required │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
ConfigurationError: redis prerequisite not available
解决方i法:pip3 install flask-redis