mirror of
https://github.com/KingHWJ/WeReadBoard.git
synced 2026-11-03 18:24:58 +08:00
feat(discovery): 完善书籍搜索推荐与日志记录
This commit is contained in:
1 parent
aee8c58b04
commit
61d3951905
4 files changed
+263
-27
No files matched your search
@@ -35,7 +35,7 @@ try:
|
||||
_ssl_context = ssl.create_default_context(cafile=certifi.where())
|
||||
except ImportError:
|
||||
_ssl_context = ssl.create_default_context()
|
||||
from flask import Flask, jsonify, render_template, request
|
||||
from flask import Flask, g, jsonify, render_template, request
|
||||
|
||||
from api_v2 import v2_bp
|
||||
|
||||
@@ -61,6 +61,60 @@ MYSQL_CONFIG = {
|
||||
"cursorclass": pymysql.cursors.DictCursor, # 使用字典游标,方便按字段名取值
|
||||
}
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 网站操作日志
|
||||
# ======================================================================
|
||||
|
||||
@app.before_request
|
||||
def start_operation_log_timer():
|
||||
"""记录请求开始时间,供 after_request 计算接口耗时。"""
|
||||
g.operation_started_at = time.perf_counter()
|
||||
|
||||
|
||||
@app.after_request
|
||||
def write_operation_log(response):
|
||||
"""将 API 请求写入 operation_logs;日志失败不影响业务响应。"""
|
||||
if not request.path.startswith("/api/"):
|
||||
return response
|
||||
|
||||
try:
|
||||
started_at = getattr(g, "operation_started_at", time.perf_counter())
|
||||
duration_ms = max(0, int((time.perf_counter() - started_at) * 1000))
|
||||
path_parts = [part for part in request.path.split("/") if part]
|
||||
action = "/".join(path_parts[-2:]) if len(path_parts) >= 2 else request.path
|
||||
target_type = path_parts[-2] if len(path_parts) >= 2 else None
|
||||
target_id = path_parts[-1] if len(path_parts) >= 2 and path_parts[-1] != target_type else None
|
||||
detail = {"query": request.args.to_dict(flat=True)}
|
||||
conn = pymysql.connect(**MYSQL_CONFIG)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO operation_logs "
|
||||
"(operation_type, action, target_type, target_id, keyword, request_path, "
|
||||
"request_method, status_code, duration_ms, detail_json) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
"api_request",
|
||||
action,
|
||||
target_type,
|
||||
target_id,
|
||||
request.args.get("keyword"),
|
||||
request.path,
|
||||
request.method,
|
||||
response.status_code,
|
||||
duration_ms,
|
||||
json.dumps(detail, ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
except Exception:
|
||||
# 日志属于旁路能力,数据库或表异常时不能影响正常页面/API 返回。
|
||||
pass
|
||||
return response
|
||||
|
||||
# ======================================================================
|
||||
# 微信读书 API 配置
|
||||
# ======================================================================
|
||||
|
||||
Reference in new issue
Block a user