flask-pluginkit-accesscount 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flask_pluginkit_accesscount/__init__.py +533 -0
- flask_pluginkit_accesscount-0.4.0.dist-info/METADATA +170 -0
- flask_pluginkit_accesscount-0.4.0.dist-info/RECORD +6 -0
- flask_pluginkit_accesscount-0.4.0.dist-info/WHEEL +5 -0
- flask_pluginkit_accesscount-0.4.0.dist-info/licenses/LICENSE +29 -0
- flask_pluginkit_accesscount-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
AccessCount
|
|
4
|
+
-----------
|
|
5
|
+
|
|
6
|
+
PV、Endpoint statistics and response time tracking plugin.
|
|
7
|
+
|
|
8
|
+
:copyright: (c) 2025 by Hiroshi.tao.
|
|
9
|
+
:license: BSD 3-Clause License, see LICENSE for more details.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import time
|
|
13
|
+
import atexit
|
|
14
|
+
import threading
|
|
15
|
+
from datetime import datetime, date, timedelta
|
|
16
|
+
from typing import Dict, Optional, Tuple, Union
|
|
17
|
+
|
|
18
|
+
from flask import current_app, request, g, jsonify
|
|
19
|
+
from flask_pluginkit import RedisStorage
|
|
20
|
+
from prettytable import PrettyTable
|
|
21
|
+
|
|
22
|
+
__plugin_name__ = "AccessCount"
|
|
23
|
+
__description__ = "IP、PV、Endpoint Statistics with Response Time"
|
|
24
|
+
__author__ = "Hiroshi.tao <me@tcw.im>"
|
|
25
|
+
__version__ = "0.4.0"
|
|
26
|
+
__license__ = "BSD 3-Clause"
|
|
27
|
+
__license_file__ = "LICENSE"
|
|
28
|
+
__readme_file__ = "README.md"
|
|
29
|
+
__url__ = "https://github.com/saintic/flask-pluginkit-accesscount"
|
|
30
|
+
__state__ = "enabled"
|
|
31
|
+
|
|
32
|
+
# 默认配置值
|
|
33
|
+
default_key_prefix: str = "pluginkit"
|
|
34
|
+
default_flush_times = 100
|
|
35
|
+
default_flush_interval = 60
|
|
36
|
+
default_min_data = 5 # 间隔刷新时最少累积多少条数据才写入
|
|
37
|
+
default_retention_days = 90 # Redis 数据保留天数
|
|
38
|
+
|
|
39
|
+
# 配置缓存:{key: (value, expire_monotonic)},默认 300s TTL
|
|
40
|
+
_config_cache: Dict[str, Tuple[Union[str, int], float]] = {}
|
|
41
|
+
_config_ttl = 300
|
|
42
|
+
|
|
43
|
+
# 线程锁:保护 _stats 的读写
|
|
44
|
+
_stats_lock = threading.Lock()
|
|
45
|
+
|
|
46
|
+
# RedisStorage 实例缓存(redis_url 模式复用连接池)
|
|
47
|
+
_cached_storage: Optional[RedisStorage] = None
|
|
48
|
+
|
|
49
|
+
# 上次清理过期字段的日期,避免每次 flush 都扫描全部 hash
|
|
50
|
+
_last_cleanup_date = ""
|
|
51
|
+
|
|
52
|
+
# 当前进程统计数据(各进程内存独立,无需 PID 嵌套)
|
|
53
|
+
# ep: {endpoint: count} 端点访问量
|
|
54
|
+
# ep_time: {endpoint: {total_ms, count}} 端点耗时
|
|
55
|
+
# pv: int 当前进程累计 PV
|
|
56
|
+
# ts: float 上次刷新的 monotonic 时间(不受 NTP 影响)
|
|
57
|
+
# times: int 累计访问次数
|
|
58
|
+
_stats: Dict = {"ep": {}, "ep_time": {}, "pv": 0, "ts": 0.0, "times": 0}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ---------------------------------------------------------------------------
|
|
62
|
+
# 配置与工具函数
|
|
63
|
+
# ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _get_config(key: str, default, ttl: int = None):
|
|
67
|
+
"""获取配置项,带 TTL 缓存。默认 300s 后自动重新读取 current_app.config"""
|
|
68
|
+
if ttl is None:
|
|
69
|
+
ttl = _config_ttl
|
|
70
|
+
now = time.monotonic()
|
|
71
|
+
if key in _config_cache:
|
|
72
|
+
val, expire = _config_cache[key]
|
|
73
|
+
if now < expire:
|
|
74
|
+
return val
|
|
75
|
+
val = current_app.config.get(key, default)
|
|
76
|
+
_config_cache[key] = (val, now + ttl)
|
|
77
|
+
return val
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _get_cached_config_value(key: str, default=None):
|
|
81
|
+
"""从缓存中取配置值(仅取值,不刷新 TTL,用于 atexit 等无 Flask 上下文的场景)"""
|
|
82
|
+
entry = _config_cache.get(key)
|
|
83
|
+
return entry[0] if entry else default
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _refresh_config_cache():
|
|
87
|
+
"""清空配置缓存,下次请求时重新读取"""
|
|
88
|
+
_config_cache.clear()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def now_ts() -> float:
|
|
92
|
+
"""获取当前 monotonic 秒(单调递增,不受系统时间/NTP 调整影响)"""
|
|
93
|
+
return time.monotonic()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def get_time(fm: str = "%Y-%m-%d %H:%M:%S") -> str:
|
|
97
|
+
"""获取当前日期时间字符串"""
|
|
98
|
+
return datetime.now().strftime(fm)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _get_storage():
|
|
102
|
+
"""获取 RedisStorage 实例,redis_url 模式缓存复用"""
|
|
103
|
+
conn_name = _get_config("PLUGINKIT_ACCESSCOUNT_REDIS_NAME", "redis")
|
|
104
|
+
redis_url = _get_config("PLUGINKIT_ACCESSCOUNT_REDIS_URL", "")
|
|
105
|
+
|
|
106
|
+
redis_conn = getattr(g, conn_name, None)
|
|
107
|
+
if redis_conn:
|
|
108
|
+
return RedisStorage(redis_connection=redis_conn)
|
|
109
|
+
|
|
110
|
+
if redis_url:
|
|
111
|
+
global _cached_storage
|
|
112
|
+
if _cached_storage is None:
|
|
113
|
+
_cached_storage = RedisStorage(redis_url=redis_url)
|
|
114
|
+
return _cached_storage
|
|
115
|
+
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ---------------------------------------------------------------------------
|
|
120
|
+
# 统计核心
|
|
121
|
+
# ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def initialize_stats():
|
|
125
|
+
"""初始化/重置当前进程的统计数据"""
|
|
126
|
+
global _stats
|
|
127
|
+
_stats = {"ep": {}, "ep_time": {}, "pv": 0, "ts": now_ts(), "times": 0}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def record_start_time():
|
|
131
|
+
"""before_request 钩子:在 g 上记录请求开始时间"""
|
|
132
|
+
g._accesscount_start = time.time()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def record_ip_pv(response):
|
|
136
|
+
"""after_request 钩子:记录 PV、端点访问量及耗时(线程安全)"""
|
|
137
|
+
global _stats
|
|
138
|
+
|
|
139
|
+
with _stats_lock:
|
|
140
|
+
_stats["times"] += 1
|
|
141
|
+
_stats["pv"] += 1
|
|
142
|
+
|
|
143
|
+
if request.endpoint:
|
|
144
|
+
_stats["ep"][request.endpoint] = _stats["ep"].get(request.endpoint, 0) + 1
|
|
145
|
+
|
|
146
|
+
start_time = getattr(g, "_accesscount_start", None)
|
|
147
|
+
if start_time is not None:
|
|
148
|
+
elapsed_ms = (time.time() - start_time) * 1000
|
|
149
|
+
if request.endpoint not in _stats["ep_time"]:
|
|
150
|
+
_stats["ep_time"][request.endpoint] = {"total_ms": 0.0, "count": 0}
|
|
151
|
+
_stats["ep_time"][request.endpoint]["total_ms"] += elapsed_ms
|
|
152
|
+
_stats["ep_time"][request.endpoint]["count"] += 1
|
|
153
|
+
|
|
154
|
+
# 检查刷新阈值
|
|
155
|
+
_flush_times = _get_config(
|
|
156
|
+
"PLUGINKIT_ACCESSCOUNT_FLUSH_TIMES", default_flush_times
|
|
157
|
+
)
|
|
158
|
+
_flush_interval = _get_config(
|
|
159
|
+
"PLUGINKIT_ACCESSCOUNT_FLUSH_INTERVAL", default_flush_interval
|
|
160
|
+
)
|
|
161
|
+
_min_data = _get_config(
|
|
162
|
+
"PLUGINKIT_ACCESSCOUNT_FLUSH_MIN_DATA", default_min_data
|
|
163
|
+
)
|
|
164
|
+
_pass_time = now_ts() - _stats["ts"]
|
|
165
|
+
|
|
166
|
+
# 两种触发条件:
|
|
167
|
+
# 1. 次数达标:累计请求 >= flush_times,且数据量 >= min_data
|
|
168
|
+
# 2. 时间达标:距上次刷新 >= flush_interval,且有实际数据
|
|
169
|
+
need_flush = (
|
|
170
|
+
(_stats["times"] >= _flush_times and _stats["pv"] >= _min_data)
|
|
171
|
+
or (_pass_time >= _flush_interval and _stats["pv"] > 0)
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
if need_flush:
|
|
175
|
+
snapshot = {
|
|
176
|
+
"ep": dict(_stats["ep"]),
|
|
177
|
+
"ep_time": {
|
|
178
|
+
k: {"total_ms": v["total_ms"], "count": v["count"]}
|
|
179
|
+
for k, v in _stats["ep_time"].items()
|
|
180
|
+
},
|
|
181
|
+
"pv": _stats["pv"],
|
|
182
|
+
}
|
|
183
|
+
initialize_stats()
|
|
184
|
+
|
|
185
|
+
if need_flush:
|
|
186
|
+
flush_to_redis(snapshot)
|
|
187
|
+
|
|
188
|
+
return response
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def flush_to_redis(data: dict):
|
|
192
|
+
"""将统计数据快照批量写入 Redis(请求上下文内调用)"""
|
|
193
|
+
if not data or data.get("pv", 0) <= 0:
|
|
194
|
+
return
|
|
195
|
+
|
|
196
|
+
today = get_time("%Y%m%d")
|
|
197
|
+
prefix = _get_config("PLUGINKIT_ACCESSCOUNT_KEY_PREFIX", default_key_prefix)
|
|
198
|
+
|
|
199
|
+
storage = _get_storage()
|
|
200
|
+
if storage is None:
|
|
201
|
+
return
|
|
202
|
+
|
|
203
|
+
_pipeline_write(data, storage, prefix, today, logger=current_app.logger)
|
|
204
|
+
|
|
205
|
+
# 每天最多执行一次过期字段清理
|
|
206
|
+
_cleanup_expired_fields(storage, prefix)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _pipeline_write(
|
|
210
|
+
data: dict,
|
|
211
|
+
storage: "RedisStorage",
|
|
212
|
+
prefix: str,
|
|
213
|
+
today: str,
|
|
214
|
+
logger=None,
|
|
215
|
+
):
|
|
216
|
+
"""底层 Redis Pipeline 批量写入(请求上下文和 atexit 共用)"""
|
|
217
|
+
pipe = storage._db.pipeline()
|
|
218
|
+
pipe.hincrby(f"{prefix}:AccessCount:pv:hash", today, data["pv"])
|
|
219
|
+
|
|
220
|
+
for ep, count in data["ep"].items():
|
|
221
|
+
pipe.hincrby(f"{prefix}:AccessCount:endpoint:hash", f"{today}:{ep}", count)
|
|
222
|
+
|
|
223
|
+
for ep, td in data["ep_time"].items():
|
|
224
|
+
total_ms = int(td["total_ms"])
|
|
225
|
+
cnt = td["count"]
|
|
226
|
+
if total_ms > 0:
|
|
227
|
+
pipe.hincrby(
|
|
228
|
+
f"{prefix}:AccessCount:endpoint:time:hash",
|
|
229
|
+
f"{today}:{ep}",
|
|
230
|
+
total_ms,
|
|
231
|
+
)
|
|
232
|
+
if cnt > 0:
|
|
233
|
+
pipe.hincrby(
|
|
234
|
+
f"{prefix}:AccessCount:endpoint:time_cnt:hash",
|
|
235
|
+
f"{today}:{ep}",
|
|
236
|
+
cnt,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# 设置 key 级别过期(兜底保障:即使清理函数未运行,90 天后自动删除整个 key)
|
|
240
|
+
ttl_seconds = 86400 * 90
|
|
241
|
+
for suffix in ("pv:hash", "endpoint:hash", "endpoint:time:hash", "endpoint:time_cnt:hash"):
|
|
242
|
+
pipe.expire(f"{prefix}:AccessCount:{suffix}", ttl_seconds)
|
|
243
|
+
|
|
244
|
+
try:
|
|
245
|
+
pipe.execute()
|
|
246
|
+
except Exception as e:
|
|
247
|
+
if logger:
|
|
248
|
+
logger.error("AccessCount plugin write data failed: %s", e)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _cleanup_expired_fields(storage: "RedisStorage", prefix: str):
|
|
252
|
+
"""删除超过 retention 天的 Redis hash 字段(每天每个进程最多执行一次)"""
|
|
253
|
+
global _last_cleanup_date
|
|
254
|
+
today = get_time("%Y%m%d")
|
|
255
|
+
if today == _last_cleanup_date:
|
|
256
|
+
return
|
|
257
|
+
|
|
258
|
+
retention = _get_config(
|
|
259
|
+
"PLUGINKIT_ACCESSCOUNT_DATA_RETENTION", default_retention_days
|
|
260
|
+
)
|
|
261
|
+
expire_date = (datetime.now() - timedelta(days=retention)).strftime("%Y%m%d")
|
|
262
|
+
|
|
263
|
+
for suffix in ("pv:hash", "endpoint:hash", "endpoint:time:hash", "endpoint:time_cnt:hash"):
|
|
264
|
+
key = f"{prefix}:AccessCount:{suffix}"
|
|
265
|
+
cursor = 0
|
|
266
|
+
to_delete = []
|
|
267
|
+
while True:
|
|
268
|
+
cursor, items = storage._db.hscan(key, cursor, count=200)
|
|
269
|
+
if items:
|
|
270
|
+
for field in items:
|
|
271
|
+
field_str = field if isinstance(field, str) else field.decode()
|
|
272
|
+
if field_str[:8] < expire_date:
|
|
273
|
+
to_delete.append(field)
|
|
274
|
+
if cursor == 0:
|
|
275
|
+
break
|
|
276
|
+
if to_delete:
|
|
277
|
+
# 分批 hdel(Redis 单次删多字段没有硬限制,但分批更安全)
|
|
278
|
+
for i in range(0, len(to_delete), 500):
|
|
279
|
+
try:
|
|
280
|
+
storage._db.hdel(key, *to_delete[i : i + 500])
|
|
281
|
+
except Exception:
|
|
282
|
+
pass
|
|
283
|
+
|
|
284
|
+
_last_cleanup_date = today
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
# ---------------------------------------------------------------------------
|
|
288
|
+
# atexit:进程退出前 flush 剩余数据,避免重启丢数据
|
|
289
|
+
# ---------------------------------------------------------------------------
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _atexit_flush():
|
|
293
|
+
"""atexit 回调:进程退出前将内存中剩余统计刷入 Redis(best-effort)"""
|
|
294
|
+
with _stats_lock:
|
|
295
|
+
if _stats.get("pv", 0) <= 0:
|
|
296
|
+
return
|
|
297
|
+
snapshot = {
|
|
298
|
+
"ep": dict(_stats["ep"]),
|
|
299
|
+
"ep_time": {
|
|
300
|
+
k: {"total_ms": v["total_ms"], "count": v["count"]}
|
|
301
|
+
for k, v in _stats["ep_time"].items()
|
|
302
|
+
},
|
|
303
|
+
"pv": _stats["pv"],
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if not snapshot["pv"]:
|
|
307
|
+
return
|
|
308
|
+
|
|
309
|
+
# 尝试获取 Redis 连接
|
|
310
|
+
storage = _cached_storage
|
|
311
|
+
if storage is None:
|
|
312
|
+
redis_url = _get_cached_config_value(
|
|
313
|
+
"PLUGINKIT_ACCESSCOUNT_REDIS_URL", ""
|
|
314
|
+
)
|
|
315
|
+
if redis_url:
|
|
316
|
+
try:
|
|
317
|
+
storage = RedisStorage(redis_url=redis_url)
|
|
318
|
+
except Exception:
|
|
319
|
+
return
|
|
320
|
+
else:
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
today = datetime.now().strftime("%Y%m%d")
|
|
324
|
+
prefix = _get_cached_config_value(
|
|
325
|
+
"PLUGINKIT_ACCESSCOUNT_KEY_PREFIX", default_key_prefix
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
_pipeline_write(snapshot, storage, prefix, today)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
atexit.register(_atexit_flush)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
# ---------------------------------------------------------------------------
|
|
335
|
+
# Flask-PluginKit 集成
|
|
336
|
+
# ---------------------------------------------------------------------------
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def register():
|
|
340
|
+
return dict(
|
|
341
|
+
hep=dict(
|
|
342
|
+
before_request=record_start_time,
|
|
343
|
+
after_request=record_ip_pv,
|
|
344
|
+
),
|
|
345
|
+
vep=dict(
|
|
346
|
+
rule="/_internal/access_count_stats",
|
|
347
|
+
view_func=lambda: jsonify(_stats),
|
|
348
|
+
endpoint="access_count_stats",
|
|
349
|
+
),
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
# ---------------------------------------------------------------------------
|
|
354
|
+
# 查询工具:数据接口 + 表格打印
|
|
355
|
+
# ---------------------------------------------------------------------------
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def dayAgo(day: int) -> str:
|
|
359
|
+
"""返回 day 天前的日期字符串 YYYY-MM-DD"""
|
|
360
|
+
return str(date.today() - timedelta(days=day))
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _get_cli_storage(redis_url: str, redis_conn):
|
|
364
|
+
"""CLI 查询工具的 RedisStorage(含参数校验)"""
|
|
365
|
+
if not redis_url and not redis_conn:
|
|
366
|
+
raise ValueError("AccessCount plugin not found valid redis url or connection.")
|
|
367
|
+
return RedisStorage(redis_url=redis_url, redis_connection=redis_conn)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
# ---- 数据接口(返回结构化 dict,供应用程序调用) ----
|
|
371
|
+
|
|
372
|
+
def get_pv(
|
|
373
|
+
day: int,
|
|
374
|
+
redis_url: str = "",
|
|
375
|
+
redis_conn=None,
|
|
376
|
+
redis_key_prefix: str = default_key_prefix,
|
|
377
|
+
) -> Dict[str, int]:
|
|
378
|
+
"""查询最近 N 天的 PV,返回 {日期: pv, ...}"""
|
|
379
|
+
day = int(day)
|
|
380
|
+
if day <= 0:
|
|
381
|
+
raise ValueError("day must be a positive integer")
|
|
382
|
+
storage = _get_cli_storage(redis_url, redis_conn)
|
|
383
|
+
dates = sorted([dayAgo(d) for d in range(0, day)])
|
|
384
|
+
key = f"{redis_key_prefix}:AccessCount:pv:hash"
|
|
385
|
+
|
|
386
|
+
pipe = storage._db.pipeline()
|
|
387
|
+
for d in dates:
|
|
388
|
+
pipe.hget(key, d.replace("-", ""))
|
|
389
|
+
values = pipe.execute()
|
|
390
|
+
return {d: (int(v) if v else 0) for d, v in zip(dates, values)}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def get_ep(
|
|
394
|
+
day: int,
|
|
395
|
+
redis_url: str = "",
|
|
396
|
+
redis_conn=None,
|
|
397
|
+
redis_key_prefix: str = default_key_prefix,
|
|
398
|
+
) -> Dict[str, Dict[str, int]]:
|
|
399
|
+
"""查询最近 N 天的端点访问量,返回 {日期: {端点: 访问量, ...}, ...}"""
|
|
400
|
+
day = int(day)
|
|
401
|
+
storage = _get_cli_storage(redis_url, redis_conn)
|
|
402
|
+
dates = sorted([dayAgo(d) for d in range(0, day)])
|
|
403
|
+
key = f"{redis_key_prefix}:AccessCount:endpoint:hash"
|
|
404
|
+
date_prefixes = {d.replace("-", ""): d for d in dates}
|
|
405
|
+
|
|
406
|
+
result: Dict[str, Dict[str, int]] = {d: {} for d in dates}
|
|
407
|
+
cursor = 0
|
|
408
|
+
while True:
|
|
409
|
+
cursor, items = storage._db.hscan(key, cursor, count=200)
|
|
410
|
+
if items:
|
|
411
|
+
for field, value in items.items():
|
|
412
|
+
field_str = field if isinstance(field, str) else field.decode()
|
|
413
|
+
prefix = field_str[:8]
|
|
414
|
+
if prefix in date_prefixes:
|
|
415
|
+
ep_name = field_str[9:]
|
|
416
|
+
result[date_prefixes[prefix]][ep_name] = int(value)
|
|
417
|
+
if cursor == 0:
|
|
418
|
+
break
|
|
419
|
+
return result
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def get_ep_time(
|
|
423
|
+
day: int,
|
|
424
|
+
redis_url: str = "",
|
|
425
|
+
redis_conn=None,
|
|
426
|
+
redis_key_prefix: str = default_key_prefix,
|
|
427
|
+
) -> Dict[str, Dict[str, Dict]]:
|
|
428
|
+
"""查询最近 N 天的端点平均耗时,返回 {日期: {端点: {avg_ms, count, total_ms}, ...}, ...}"""
|
|
429
|
+
day = int(day)
|
|
430
|
+
storage = _get_cli_storage(redis_url, redis_conn)
|
|
431
|
+
dates = sorted([dayAgo(d) for d in range(0, day)])
|
|
432
|
+
time_key = f"{redis_key_prefix}:AccessCount:endpoint:time:hash"
|
|
433
|
+
cnt_key = f"{redis_key_prefix}:AccessCount:endpoint:time_cnt:hash"
|
|
434
|
+
date_prefixes = {d.replace("-", ""): d for d in dates}
|
|
435
|
+
|
|
436
|
+
# 扫描耗时 hash
|
|
437
|
+
result: Dict[str, Dict[str, Dict]] = {d: {} for d in dates}
|
|
438
|
+
all_fields = []
|
|
439
|
+
cursor = 0
|
|
440
|
+
while True:
|
|
441
|
+
cursor, items = storage._db.hscan(time_key, cursor, count=200)
|
|
442
|
+
if items:
|
|
443
|
+
for field, value in items.items():
|
|
444
|
+
field_str = field if isinstance(field, str) else field.decode()
|
|
445
|
+
prefix = field_str[:8]
|
|
446
|
+
if prefix in date_prefixes:
|
|
447
|
+
ep_name = field_str[9:]
|
|
448
|
+
result[date_prefixes[prefix]][ep_name] = {
|
|
449
|
+
"total_ms": float(value) if value else 0.0
|
|
450
|
+
}
|
|
451
|
+
all_fields.append(field_str)
|
|
452
|
+
if cursor == 0:
|
|
453
|
+
break
|
|
454
|
+
|
|
455
|
+
# hmget 一次取回所有 count
|
|
456
|
+
if all_fields:
|
|
457
|
+
count_values = storage._db.hmget(cnt_key, all_fields)
|
|
458
|
+
for f, v in zip(all_fields, count_values):
|
|
459
|
+
date_str, ep_name = f[:8], f[9:]
|
|
460
|
+
if date_str in date_prefixes:
|
|
461
|
+
cnt = int(v) if v else 0
|
|
462
|
+
d = date_prefixes[date_str]
|
|
463
|
+
total_ms = result[d][ep_name]["total_ms"]
|
|
464
|
+
result[d][ep_name]["count"] = cnt
|
|
465
|
+
result[d][ep_name]["avg_ms"] = (
|
|
466
|
+
round(total_ms / cnt, 2) if cnt > 0 else 0.0
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
return result
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
# ---- 表格打印(复用数据接口) ----
|
|
473
|
+
|
|
474
|
+
def print_pv(
|
|
475
|
+
day: int,
|
|
476
|
+
redis_url: str = "",
|
|
477
|
+
redis_conn=None,
|
|
478
|
+
redis_key_prefix: str = default_key_prefix,
|
|
479
|
+
):
|
|
480
|
+
"""PV 访问量表格输出"""
|
|
481
|
+
data = get_pv(day, redis_url, redis_conn, redis_key_prefix)
|
|
482
|
+
dates = sorted(data.keys())
|
|
483
|
+
values = [data[d] for d in dates]
|
|
484
|
+
avg = int(sum(values) / day)
|
|
485
|
+
|
|
486
|
+
table = PrettyTable(dates + ["平均"])
|
|
487
|
+
table.add_row(values + [avg])
|
|
488
|
+
print(table)
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def print_ep(
|
|
492
|
+
day: int,
|
|
493
|
+
redis_url: str = "",
|
|
494
|
+
redis_conn=None,
|
|
495
|
+
redis_key_prefix: str = default_key_prefix,
|
|
496
|
+
):
|
|
497
|
+
"""端点访问量表格输出"""
|
|
498
|
+
data = get_ep(day, redis_url, redis_conn, redis_key_prefix)
|
|
499
|
+
dates = sorted(data.keys())
|
|
500
|
+
|
|
501
|
+
table = PrettyTable(dates)
|
|
502
|
+
row = []
|
|
503
|
+
for d in dates:
|
|
504
|
+
subtable = PrettyTable(["端点", "访问量"])
|
|
505
|
+
for ep, cnt in sorted(data[d].items(), key=lambda x: x[1], reverse=True):
|
|
506
|
+
subtable.add_row([ep, cnt])
|
|
507
|
+
row.append(subtable)
|
|
508
|
+
table.add_row(row)
|
|
509
|
+
print(table)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def print_ep_time(
|
|
513
|
+
day: int,
|
|
514
|
+
redis_url: str = "",
|
|
515
|
+
redis_conn=None,
|
|
516
|
+
redis_key_prefix: str = default_key_prefix,
|
|
517
|
+
):
|
|
518
|
+
"""端点平均耗时表格输出"""
|
|
519
|
+
data = get_ep_time(day, redis_url, redis_conn, redis_key_prefix)
|
|
520
|
+
dates = sorted(data.keys())
|
|
521
|
+
|
|
522
|
+
table = PrettyTable(dates)
|
|
523
|
+
row = []
|
|
524
|
+
for d in dates:
|
|
525
|
+
subtable = PrettyTable(["端点", "平均耗时(ms)", "请求数"])
|
|
526
|
+
ep_list = sorted(
|
|
527
|
+
data[d].items(), key=lambda x: x[1].get("avg_ms", 0), reverse=True
|
|
528
|
+
)
|
|
529
|
+
for ep_name, info in ep_list:
|
|
530
|
+
subtable.add_row([ep_name, info["avg_ms"], info["count"]])
|
|
531
|
+
row.append(subtable)
|
|
532
|
+
table.add_row(row)
|
|
533
|
+
print(table)
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: flask-pluginkit-accesscount
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: IP、PV、Endpoint Statistics with Response Time
|
|
5
|
+
Home-page: https://github.com/saintic/flask-pluginkit-accesscount
|
|
6
|
+
Download-URL: https://github.com/saintic/flask-pluginkit-accesscount
|
|
7
|
+
Author: Hiroshi.tao
|
|
8
|
+
Author-email: me@tcw.im
|
|
9
|
+
Keywords: flask-pluginkit
|
|
10
|
+
Classifier: Environment :: Web Environment
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: Flask-PluginKit>=3.8.0
|
|
25
|
+
Requires-Dist: prettytable>=3.16.0
|
|
26
|
+
Dynamic: author
|
|
27
|
+
Dynamic: author-email
|
|
28
|
+
Dynamic: classifier
|
|
29
|
+
Dynamic: description
|
|
30
|
+
Dynamic: description-content-type
|
|
31
|
+
Dynamic: download-url
|
|
32
|
+
Dynamic: home-page
|
|
33
|
+
Dynamic: keywords
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
Dynamic: requires-dist
|
|
36
|
+
Dynamic: summary
|
|
37
|
+
|
|
38
|
+
# AccessCount
|
|
39
|
+
|
|
40
|
+
PV、Endpoint 统计与接口耗时追踪插件
|
|
41
|
+
|
|
42
|
+
基于 Flask-PluginKit 框架,采用**进程内存缓冲 + 批量刷入 Redis** 架构,兼顾统计准确性与写入性能。
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## 功能
|
|
47
|
+
|
|
48
|
+
- **PV 统计**:按天统计页面浏览量
|
|
49
|
+
- **Endpoint 统计**:按天统计各 API 端点访问量
|
|
50
|
+
- **接口耗时**:记录每个请求耗时,查询各端点平均响应时间
|
|
51
|
+
- **表格打印**:CLI 工具,`print_pv` / `print_ep` / `print_ep_time`
|
|
52
|
+
- **数据接口**:`get_pv` / `get_ep` / `get_ep_time` 返回结构化 dict,供应用程序二次消费
|
|
53
|
+
- **自动过期**:Redis 中超过 90 天的数据自动清理(可配置)
|
|
54
|
+
- **优雅退出**:进程退出前自动 flush 内存中剩余数据,避免重启丢数
|
|
55
|
+
- **线程安全**:`threading.Lock` 保护内存统计,适配多线程 Worker
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
### Development
|
|
62
|
+
|
|
63
|
+
`pip install git+https://github.com/saintic/flask-pluginkit-accesscount@master`
|
|
64
|
+
|
|
65
|
+
### PyPi Release
|
|
66
|
+
|
|
67
|
+
`pip install flask-pluginkit-accesscount`
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Usage
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from flask_pluginkit import PluginManager
|
|
75
|
+
|
|
76
|
+
PluginManager(
|
|
77
|
+
plugin_packages=["flask_pluginkit_accesscount"],
|
|
78
|
+
install_packages=dict(pkgs=["flask-pluginkit-accesscount"]),
|
|
79
|
+
)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## Configuration
|
|
85
|
+
|
|
86
|
+
Flask Config 配置项:
|
|
87
|
+
|
|
88
|
+
| 配置键 | 类型 | 默认值 | 说明 |
|
|
89
|
+
|---|---|---|---|
|
|
90
|
+
| `PLUGINKIT_ACCESSCOUNT_FLUSH_TIMES` | int | 100 | 累计多少次请求后刷入 Redis |
|
|
91
|
+
| `PLUGINKIT_ACCESSCOUNT_FLUSH_INTERVAL` | int | 60 | 累计多少秒后刷入 Redis |
|
|
92
|
+
| `PLUGINKIT_ACCESSCOUNT_FLUSH_MIN_DATA` | int | 5 | 间隔触发刷入时最少累积多少条数据 |
|
|
93
|
+
| `PLUGINKIT_ACCESSCOUNT_KEY_PREFIX` | str | `pluginkit` | Redis key 前缀 |
|
|
94
|
+
| `PLUGINKIT_ACCESSCOUNT_REDIS_NAME` | str | `redis` | Redis 连接名称(从 Flask `g` 获取) |
|
|
95
|
+
| `PLUGINKIT_ACCESSCOUNT_REDIS_URL` | str | 无 | Redis 直连 URL(与 REDIS_NAME 二选一) |
|
|
96
|
+
| `PLUGINKIT_ACCESSCOUNT_DATA_RETENTION` | int | 90 | Redis 数据保留天数 |
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## 内置路由
|
|
101
|
+
|
|
102
|
+
| 路由 | 说明 |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `/_internal/access_count_stats` | 返回当前进程内存中的统计数据 JSON |
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## CLI 查询工具
|
|
109
|
+
|
|
110
|
+
用于命令行查询 Redis 中的统计数据:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from flask_pluginkit_accesscount import print_pv, print_ep, print_ep_time
|
|
114
|
+
from flask import current_app
|
|
115
|
+
|
|
116
|
+
# 查看最近 7 天的 PV
|
|
117
|
+
print_pv(7, redis_url="redis://localhost:6379/0")
|
|
118
|
+
|
|
119
|
+
# 查看最近 7 天的端点访问量
|
|
120
|
+
print_ep(7, redis_url="redis://localhost:6379/0")
|
|
121
|
+
|
|
122
|
+
# 查看最近 7 天的端点平均耗时
|
|
123
|
+
print_ep_time(7, redis_url="redis://localhost:6379/0")
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## 数据接口
|
|
129
|
+
|
|
130
|
+
返回结构化 dict,供应用程序自定义展示、告警、导出:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from flask_pluginkit_accesscount import get_pv, get_ep, get_ep_time
|
|
134
|
+
|
|
135
|
+
# PV:返回 {"2026-12-06": 150, "2026-12-05": 200, ...}
|
|
136
|
+
data = get_pv(7, redis_url="redis://localhost:6379/0")
|
|
137
|
+
|
|
138
|
+
# 端点访问量:返回 {"2026-12-06": {"/api/users": 50, ...}, ...}
|
|
139
|
+
data = get_ep(7, redis_url="redis://localhost:6379/0")
|
|
140
|
+
|
|
141
|
+
# 平均耗时:返回 {"2026-12-06": {"/api/users": {"avg_ms": 45.2, "count": 100, "total_ms": 4520}, ...}, ...}
|
|
142
|
+
data = get_ep_time(7, redis_url="redis://localhost:6379/0")
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## Redis 存储结构
|
|
148
|
+
|
|
149
|
+
```
|
|
150
|
+
{prefix}:AccessCount:pv:hash → Hash: {YYYYMMDD: PV}
|
|
151
|
+
{prefix}:AccessCount:endpoint:hash → Hash: {YYYYMMDD:endpoint: 访问量}
|
|
152
|
+
{prefix}:AccessCount:endpoint:time:hash → Hash: {YYYYMMDD:endpoint: 总耗时(ms)}
|
|
153
|
+
{prefix}:AccessCount:endpoint:time_cnt:hash → Hash: {YYYYMMDD:endpoint: 请求次数}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 架构说明
|
|
159
|
+
|
|
160
|
+
每个 HTTP 请求在 `after_request` 钩子中累加计数到进程内存,满足阈值(次数或时间)后通过 **Redis Pipeline** 批量写入。避免每次请求都直连 Redis,保证高并发下的写入性能。
|
|
161
|
+
|
|
162
|
+
进程退出时(正常关闭、SIGTERM、Worker 回收),`atexit` 回调自动将内存中剩余数据刷入 Redis,避免重启丢数。
|
|
163
|
+
|
|
164
|
+
超过 `PLUGINKIT_ACCESSCOUNT_DATA_RETENTION` 天(默认 90 天)的数据会自动清理 — 包括字段级精准删除和 key 级 TTL 兜底。
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## License
|
|
169
|
+
|
|
170
|
+
BSD 3-Clause
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
flask_pluginkit_accesscount/__init__.py,sha256=F2JBfH7i7-w1bJfqfNeLAgLeMvpzZsSILXBAaCoMP2w,17580
|
|
2
|
+
flask_pluginkit_accesscount-0.4.0.dist-info/licenses/LICENSE,sha256=XYd7DYb-ENVHnds2haAmJU1hWNa2Bt3Y-SvK2wGh9sw,1523
|
|
3
|
+
flask_pluginkit_accesscount-0.4.0.dist-info/METADATA,sha256=_B_psxiyirBikESsIy_T-293si62oGUbfq4HVEIfMGE,5485
|
|
4
|
+
flask_pluginkit_accesscount-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
flask_pluginkit_accesscount-0.4.0.dist-info/top_level.txt,sha256=dz5TzCECwJcB9_3aL9sUeNF4Z6msXojszGaJbayobB8,28
|
|
6
|
+
flask_pluginkit_accesscount-0.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019, Flask-PluginKit
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
10
|
+
list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
17
|
+
contributors may be used to endorse or promote products derived from
|
|
18
|
+
this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
21
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
22
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
23
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
24
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
25
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
26
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
27
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
28
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
29
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
flask_pluginkit_accesscount
|