完善媒体解析流程并优化相关处理逻辑

This commit is contained in:
ucmao
2026-09-09 19:11:58 +08:00
parent 60f9495178
commit 0ac0d5fa11
13 changed files with 876 additions and 194 deletions
+33 -26
View File
@@ -1,8 +1,9 @@
import csv
from datetime import datetime, time, timedelta, timezone
import io
from zoneinfo import ZoneInfo
from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, stream_with_context, url_for
from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, url_for
from werkzeug.security import generate_password_hash
@@ -781,11 +782,6 @@ def _safe_csv_cell(value):
return text
class _CsvRowBuffer:
def write(self, value):
return value
@bp.get("/logs/export.csv")
@admin_required
def export_logs():
@@ -828,30 +824,41 @@ def export_logs():
where_sql = (" WHERE " + " AND ".join(where_clauses)) if where_clauses else ""
def generate():
writer = csv.writer(_CsvRowBuffer())
yield "\ufeff"
yield writer.writerow(("时间", "客户", "Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码"))
cursor = db.execute(
f"SELECT l.*, u.username, k.key_prefix FROM request_logs l "
f"LEFT JOIN users u ON u.id=l.user_id LEFT JOIN api_keys k ON k.id=l.api_key_id "
f"{where_sql} ORDER BY l.id DESC",
params,
)
while rows := cursor.fetchmany(1000):
for row in rows:
yield writer.writerow(tuple(_safe_csv_cell(value) for value in (
format_log_time(row["created_at"]), row["username"] or "在线体验",
f"{row['key_prefix']}••••••••••••" if row["key_prefix"] else "", row["platform"] or "", row["path"],
row["input_url"] or "", row["status_code"], row["duration_ms"],
row["error_code"] or "",
)))
output = io.StringIO()
output.write("\ufeff")
writer = csv.writer(output, lineterminator="\r\n")
writer.writerow(("时间", "客户", "Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码"))
cursor = db.execute(
f"SELECT l.*, u.username, k.key_prefix FROM request_logs l "
f"LEFT JOIN users u ON u.id=l.user_id LEFT JOIN api_keys k ON k.id=l.api_key_id "
f"{where_sql} ORDER BY l.id DESC",
params,
)
while rows := cursor.fetchmany(1000):
for row in rows:
writer.writerow((
_safe_csv_cell(format_log_time(row["created_at"])),
_safe_csv_cell(row["username"] or "在线体验"),
_safe_csv_cell(f"{row['key_prefix']}••••••••••••" if row["key_prefix"] else ""),
_safe_csv_cell(row["platform"] or ""),
_safe_csv_cell(row["path"]),
_safe_csv_cell(row["input_url"] or ""),
_safe_csv_cell(row["status_code"]),
_safe_csv_cell(row["duration_ms"]),
_safe_csv_cell(row["error_code"] or ""),
))
csv_bytes = output.getvalue().encode("utf-8")
filename = datetime.now(ZoneInfo("Asia/Shanghai")).strftime("request-logs-%Y%m%d-%H%M%S.csv")
return Response(
stream_with_context(generate()),
csv_bytes,
content_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"Content-Length": str(len(csv_bytes)),
"Cache-Control": "no-cache, no-store, must-revalidate",
},
)
+71 -42
View File
@@ -1,8 +1,9 @@
import csv
from datetime import datetime, time, timezone
import io
from zoneinfo import ZoneInfo
from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, stream_with_context, url_for
from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, url_for
from configs.general_constants import DOMAIN_TO_NAME
from src.auth import csrf_protected, format_log_time, generate_api_key, hash_api_key, login_required, user_is_expired
@@ -417,53 +418,81 @@ def _safe_csv_cell(value):
return text
class _CsvRowBuffer:
def write(self, value):
return value
@bp.get("/logs/export.csv")
@login_required
def export_logs():
db = get_db()
export_type = request.args.get("export_type", "all")
ids_param = request.args.get("ids", "").strip()
selected_ids = []
if ids_param:
try:
selected_ids = [int(i.strip()) for i in ids_param.split(",") if i.strip().isdigit()]
except ValueError:
selected_ids = []
def generate():
writer = csv.writer(_CsvRowBuffer())
yield "\ufeff"
yield writer.writerow(("时间", "调用 Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码"))
db = get_db()
if selected_ids:
placeholders = ",".join(["?"] * len(selected_ids))
sql = f"""SELECT l.*, k.key_prefix, k.name as key_name
FROM request_logs l
LEFT JOIN api_keys k ON l.api_key_id = k.id
WHERE l.user_id=? AND l.id IN ({placeholders})
ORDER BY l.id DESC"""
cursor = db.execute(sql, [g.user["id"]] + selected_ids)
else:
sql = """SELECT l.*, k.key_prefix, k.name as key_name
FROM request_logs l
LEFT JOIN api_keys k ON l.api_key_id = k.id
WHERE l.user_id=?
ORDER BY l.id DESC"""
cursor = db.execute(sql, (g.user["id"],))
while rows := cursor.fetchmany(1000):
for row in rows:
key_display = f"{row['key_name']} ({row['key_prefix']}...)" if row["key_prefix"] else "Web 免鉴权"
yield writer.writerow(tuple(_safe_csv_cell(value) for value in (
format_log_time(row["created_at"]), key_display, row["platform"] or "", row["path"],
row["input_url"] or "", row["status_code"], row["duration_ms"],
row["error_code"] or "",
)))
where_clauses, params = ["l.user_id = ?"], [g.user["id"]]
if export_type == "selected" and ids_param:
try:
id_list = [int(i.strip()) for i in ids_param.split(",") if i.strip().isdigit()]
if id_list:
placeholders = ",".join(["?"] * len(id_list))
where_clauses.append(f"l.id IN ({placeholders})")
params.extend(id_list)
except ValueError:
pass
else:
if l_q := request.args.get("logs_q", request.args.get("q", "")).strip():
where_clauses.append("(l.input_url LIKE ? OR l.error_code LIKE ? OR k.name LIKE ?)")
params.extend([f"%{l_q}%", f"%{l_q}%", f"%{l_q}%"])
if l_status := request.args.get("logs_status", request.args.get("status_code", "")).strip():
if l_status == "200":
where_clauses.append("l.status_code < 400")
elif l_status == "error":
where_clauses.append("l.status_code >= 400")
elif l_status.isdigit():
where_clauses.append("l.status_code = ?")
params.append(int(l_status))
if l_platform := request.args.get("logs_platform", request.args.get("platform", "")).strip():
where_clauses.append("l.platform = ?")
params.append(l_platform)
if utc_start := _parse_shanghai_to_utc_iso(request.args.get("logs_start_date", request.args.get("start_date", "")), is_end=False):
where_clauses.append("l.created_at >= ?")
params.append(utc_start)
if utc_end := _parse_shanghai_to_utc_iso(request.args.get("logs_end_date", request.args.get("end_date", "")), is_end=True):
where_clauses.append("l.created_at <= ?")
params.append(utc_end)
where_sql = " WHERE " + " AND ".join(where_clauses)
output = io.StringIO()
output.write("\ufeff")
writer = csv.writer(output, lineterminator="\r\n")
writer.writerow(("时间", "调用 Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码"))
sql = f"""SELECT l.*, k.key_prefix, k.name as key_name
FROM request_logs l
LEFT JOIN api_keys k ON l.api_key_id = k.id
{where_sql}
ORDER BY l.id DESC"""
cursor = db.execute(sql, params)
while rows := cursor.fetchmany(1000):
for row in rows:
key_display = f"{row['key_name']} ({row['key_prefix']}...)" if row["key_prefix"] else "Web 免鉴权"
writer.writerow((
_safe_csv_cell(format_log_time(row["created_at"])),
_safe_csv_cell(key_display),
_safe_csv_cell(row["platform"] or ""),
_safe_csv_cell(row["path"]),
_safe_csv_cell(row["input_url"] or ""),
_safe_csv_cell(row["status_code"]),
_safe_csv_cell(row["duration_ms"]),
_safe_csv_cell(row["error_code"] or ""),
))
csv_bytes = output.getvalue().encode("utf-8")
filename = datetime.now(ZoneInfo("Asia/Shanghai")).strftime("my-request-logs-%Y%m%d-%H%M%S.csv")
return Response(
stream_with_context(generate()),
csv_bytes,
content_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"Content-Length": str(len(csv_bytes)),
"Cache-Control": "no-cache, no-store, must-revalidate",
},
)
+420 -50
View File
@@ -648,6 +648,16 @@ input:not([type="checkbox"]):not([type="radio"]), select, textarea {
transition: all 0.15s ease;
}
select {
appearance: none;
-webkit-appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 12px center;
padding-right: 32px !important;
cursor: pointer;
}
input:not([type="checkbox"]):not([type="radio"]):focus, select:focus, textarea:focus {
outline: none;
border-color: var(--brand);
@@ -1651,6 +1661,17 @@ table input[type="number"] {
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
list-style: none;
cursor: pointer;
user-select: none;
}
.api-tip-preview-header::-webkit-details-marker {
display: none;
}
details.api-tip-preview-box:not([open]) .api-tip-preview-header {
margin-bottom: 0;
}
.api-tip-preview-title {
@@ -2081,6 +2102,8 @@ table input[type="number"] {
.table-filter-form select {
min-width: 110px !important;
background-position: right 8px center !important;
padding-right: 26px !important;
}
.th-sortable {
@@ -2107,6 +2130,19 @@ table input[type="number"] {
font-weight: bold;
}
.error-code-badge {
display: inline-block;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 11.5px;
font-weight: 500;
color: var(--ink-secondary);
background: var(--bg-subtle);
border: 1px solid var(--line);
padding: 1.5px 6px;
border-radius: var(--radius-xs);
letter-spacing: -0.2px;
}
.table-selection-banner {
display: none;
align-items: center;
@@ -2160,12 +2196,13 @@ table input[type="number"] {
.page-size-select {
width: auto !important;
height: 30px !important;
min-width: 76px !important;
padding: 0 8px !important;
min-width: 86px !important;
padding: 0 24px 0 8px !important;
background-position: right 6px center !important;
font-size: 12px !important;
border-radius: var(--radius-sm) !important;
border: 1px solid #cbd5e1 !important;
background: var(--bg-card) !important;
background-color: var(--bg-card) !important;
color: var(--ink) !important;
cursor: pointer;
}
@@ -2348,27 +2385,28 @@ table input[type="number"] {
.api-docs-container {
display: flex;
flex-direction: column;
max-width: 1160px;
margin: 0 auto;
padding: 8px 36px 80px;
width: 100%;
margin: 0;
padding: 0;
}
/* 纯净无卡片无边界文档画布 (Seamless Canvas) */
/* 统一独立纯白技术文档大画布卡片 (Whitepaper Document Card Canvas) - 与全站 .card 间距完全一致 */
.api-docs-canvas {
background: transparent;
border: none;
border-radius: 0;
box-shadow: none;
background: var(--bg-card);
border: 1px solid var(--line);
border-radius: var(--radius-xl);
padding: 22px 24px;
box-shadow: var(--shadow-xs);
transition: box-shadow 0.2s ease, border-color 0.2s ease;
overflow: visible;
}
/* 顶部强化 Endpoint Hero Header */
.api-endpoint-hero {
padding: 12px 0 24px;
padding: 0 0 20px;
background: transparent;
border-bottom: 1px solid var(--line);
margin-bottom: 28px;
margin-bottom: 24px;
}
.api-hero-main-row {
@@ -2437,7 +2475,7 @@ table input[type="number"] {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 56px;
gap: 36px;
position: relative;
}
@@ -2445,10 +2483,9 @@ table input[type="number"] {
.api-doc-article {
flex: 1;
min-width: 0;
max-width: 860px;
display: flex;
flex-direction: column;
gap: 44px;
gap: 36px;
}
.api-doc-section {
@@ -2457,7 +2494,7 @@ table input[type="number"] {
/* 右侧粘性固定目录 (On this page) */
.api-doc-toc-wrap {
width: 200px;
width: 190px;
flex-shrink: 0;
position: sticky;
top: calc(var(--topbar-height) + 24px);
@@ -2504,25 +2541,10 @@ table input[type="number"] {
border-left-color: var(--brand);
}
@media (max-width: 1200px) {
.api-docs-container {
padding: 8px 24px 60px;
}
}
@media (max-width: 1080px) {
.api-doc-toc-wrap {
display: none !important;
}
.api-doc-article {
max-width: 100%;
}
}
@media (max-width: 768px) {
.api-docs-container {
padding: 4px 10px 40px;
}
}
.doc-section-title {
@@ -2550,37 +2572,43 @@ table input[type="number"] {
margin: 0 0 14px;
}
/* 扁平化数据表格 */
/* 纯净文档排版数据表格 (Technical Documentation Table) */
.doc-flat-table-wrap {
overflow-x: auto;
margin: 12px 0 18px;
margin: 14px 0 20px;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.doc-flat-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
font-size: 13.5px;
text-align: left;
}
.doc-flat-table th {
background: transparent;
color: var(--ink-muted);
font-weight: 600;
background: #f8fafc;
color: var(--ink-secondary);
font-weight: 650;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 8px 12px 10px;
border-bottom: 2px solid var(--line);
padding: 10px 14px;
border-bottom: 1px solid var(--line);
white-space: nowrap;
}
.doc-flat-table td {
padding: 11px 12px;
padding: 12px 14px;
border-bottom: 1px solid var(--line-subtle);
color: var(--ink);
vertical-align: top;
line-height: 1.5;
line-height: 1.6;
}
.doc-flat-table tr:last-child td {
border-bottom: none;
}
.doc-flat-table td:nth-child(1),
@@ -2588,8 +2616,26 @@ table input[type="number"] {
white-space: nowrap;
}
/* 纯净文档排版:彻底移除表格行悬浮变色(强制覆盖全局 tbody tr:hover) */
.doc-flat-table tbody tr,
.doc-flat-table tbody tr:hover,
.doc-flat-table tr,
.doc-flat-table tr:hover,
.doc-flat-table td,
.doc-flat-table tr:hover td {
background: #f8fafc;
background: transparent !important;
background-color: transparent !important;
transition: none !important;
}
.api-doc-article :not(pre) > code {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12.5px;
background: var(--bg-subtle);
color: var(--ink);
padding: 1.5px 5.5px;
border-radius: var(--radius-xs);
border: 1px solid var(--line);
}
.param-req {
@@ -2992,20 +3038,155 @@ textarea.pg-input {
border: none !important;
}
.pg-key-dropdown {
/* Playground Key Selector Custom Dropdown */
.pg-key-dropdown-wrap {
position: absolute;
right: 6px;
top: 50%;
transform: translateY(-50%);
height: 26px;
z-index: 25;
}
.pg-key-dropdown-trigger {
display: inline-flex;
align-items: center;
gap: 5px;
height: 28px;
padding: 0 9px;
font-size: 11.5px;
border-radius: var(--radius-sm);
border: 1px solid var(--line);
background: var(--bg-subtle);
font-weight: 500;
color: var(--ink-secondary);
padding: 0 6px;
background: var(--bg-subtle);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
cursor: pointer;
max-width: 155px;
transition: all 0.15s ease;
user-select: none;
max-width: 160px;
}
.pg-key-dropdown-trigger:hover,
.pg-key-dropdown-wrap.open .pg-key-dropdown-trigger {
border-color: var(--brand-border);
color: var(--brand);
background: var(--brand-light);
}
.pg-key-dropdown-chevron {
flex-shrink: 0;
color: var(--ink-muted);
transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), color 0.15s ease;
}
.pg-key-dropdown-wrap.open .pg-key-dropdown-chevron {
transform: rotate(180deg);
color: var(--brand);
}
.pg-key-dropdown-menu {
position: absolute;
top: calc(100% + 5px);
right: 0;
min-width: 175px;
width: max-content;
max-width: 240px;
max-height: 280px;
background: var(--bg-card);
border: 1px solid var(--line);
border-radius: var(--radius-md);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.12), 0 8px 10px -6px rgba(0, 0, 0, 0.08);
padding: 4px;
z-index: 1000;
display: none;
overflow-y: auto;
box-sizing: border-box;
}
.pg-key-dropdown-wrap.open .pg-key-dropdown-menu {
display: block;
animation: pgKeyMenuFadeIn 0.15s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes pgKeyMenuFadeIn {
from {
opacity: 0;
transform: translateY(-4px) scale(0.98);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
.pg-key-menu-divider {
height: 1px;
background: var(--line);
margin: 4px 0;
}
.pg-key-menu-item {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 6px 9px;
border-radius: var(--radius-sm);
background: transparent;
border: none;
text-align: left;
cursor: pointer;
transition: background 0.12s ease;
box-sizing: border-box;
font-size: 12.5px;
color: var(--ink);
}
.pg-key-menu-item:hover {
background: var(--bg-subtle);
}
.pg-key-menu-item.active {
background: var(--brand-light);
color: var(--brand);
}
.pg-key-menu-item .pg-key-item-title {
font-size: 12.5px;
font-weight: 400;
color: inherit;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
}
.pg-key-menu-item.active .pg-key-item-title {
font-weight: 600;
color: var(--brand);
}
.pg-key-item-check {
color: var(--brand);
flex-shrink: 0;
opacity: 0;
}
.pg-key-menu-item.active .pg-key-item-check {
opacity: 1;
}
.pg-key-menu-item.action-create {
display: flex;
align-items: center;
color: var(--brand);
font-size: 12px;
font-weight: 500;
padding: 6px 9px;
}
.pg-key-menu-item.action-create:hover {
background: var(--brand-light);
}
.pg-mode-toggle {
@@ -3119,6 +3300,195 @@ textarea.pg-input {
border-radius: 4px;
}
/* ==========================================================================
Clean Minimalist Custom Select Dropdown (Universal Web Dropdown)
========================================================================== */
.custom-select-wrap {
position: relative;
display: inline-flex;
align-items: center;
vertical-align: middle;
box-sizing: border-box;
}
.custom-select-btn {
display: inline-flex;
align-items: center;
justify-content: space-between;
gap: 6px;
height: 34px;
padding: 0 10px;
background: var(--bg-card);
border: 1px solid #cbd5e1;
border-radius: var(--radius-md);
color: var(--ink);
font-size: 13px;
font-weight: 400;
cursor: pointer;
user-select: none;
transition: all 0.15s ease;
white-space: nowrap;
box-sizing: border-box;
text-align: left;
}
.custom-select-btn:hover {
border-color: var(--brand-border);
background: var(--bg-subtle);
}
.custom-select-wrap.open .custom-select-btn {
border-color: var(--brand);
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.12);
background: var(--bg-card);
}
.custom-select-btn-text {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.custom-select-chevron {
color: #94a3b8;
flex-shrink: 0;
transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), color 0.15s ease;
}
.custom-select-wrap.open .custom-select-chevron {
transform: rotate(180deg);
color: var(--brand);
}
.custom-select-popover {
position: absolute;
top: calc(100% + 4px);
left: 0;
min-width: 100%;
width: max-content;
max-width: 320px;
max-height: 240px;
background: var(--bg-card);
border: 1px solid var(--line);
border-radius: var(--radius-md);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.12), 0 8px 10px -6px rgba(0, 0, 0, 0.08);
padding: 4px;
z-index: 1000;
display: none;
overflow-y: auto;
box-sizing: border-box;
}
.custom-select-wrap.open .custom-select-popover {
display: block;
animation: csFadeIn 0.15s cubic-bezier(0.16, 1, 0.3, 1);
}
.custom-select-wrap.drop-up .custom-select-popover {
top: auto;
bottom: calc(100% + 4px);
}
@keyframes csFadeIn {
from {
opacity: 0;
transform: translateY(-3px) scale(0.98);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
.custom-select-group-header {
padding: 6px 10px 2px;
font-size: 11px;
font-weight: 700;
color: var(--ink-muted);
user-select: none;
}
.custom-select-item {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 6px 10px;
border-radius: var(--radius-sm);
background: transparent;
border: none;
text-align: left;
cursor: pointer;
transition: background 0.12s ease;
box-sizing: border-box;
font-size: 13px;
color: var(--ink);
white-space: nowrap;
}
.custom-select-item:hover {
background: var(--bg-subtle);
}
.custom-select-item.active {
background: var(--brand-light);
color: var(--brand);
font-weight: 500;
}
.custom-select-item-text {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.custom-select-item-check {
color: var(--brand);
flex-shrink: 0;
opacity: 0;
}
.custom-select-item.active .custom-select-item-check {
opacity: 1;
}
/* Modifiers for pagination and form sizes */
.pagination-info .custom-select-btn,
.page-size-selector .custom-select-btn {
height: 28px !important;
padding: 0 8px !important;
font-size: 12px !important;
border-radius: var(--radius-sm) !important;
background: var(--bg-card);
}
.pagination-info .custom-select-item,
.page-size-selector .custom-select-item {
padding: 5px 8px !important;
font-size: 12px !important;
}
.table-filter-form .custom-select-wrap {
min-width: 105px;
}
.field .custom-select-wrap {
width: 100%;
}
.field .custom-select-btn {
width: 100%;
height: 38px;
}
.modal-card .custom-select-popover {
z-index: 1200;
}
+207 -7
View File
@@ -3,6 +3,9 @@
* 通用后台数据表格交互核心逻辑:排序、动态筛选、批量勾选/跨页全选、分页及条数切换、导出。
*/
function initAll() {
// 初始化页面自定义下拉组件
initCustomSelects();
// 监听全选框与单选框联动
initTableSelection();
@@ -301,7 +304,7 @@ function setSelectAllFilteredMode(tableId, totalCount) {
/**
* 核心批量操作提交接口
*/
function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, confirmPrompt = '') {
async function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, confirmPrompt = '', confirmTitle = '操作确认', confirmType = 'danger') {
const table = document.getElementById(tableId);
if (!table) return;
@@ -310,12 +313,24 @@ function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, confi
const values = Array.from(checkedBoxes).map(cb => cb.value);
if (!isAllMode && values.length === 0) {
alert('请先勾选需要批量操作的行!');
if (window.showToast) {
window.showToast('请先勾选需要批量操作的行!', 'warning');
}
return;
}
if (confirmPrompt && !confirm(confirmPrompt)) {
return;
if (confirmPrompt) {
if (window.confirmModal) {
const ok = await window.confirmModal({
title: confirmTitle,
message: confirmPrompt,
confirmText: '确定',
type: confirmType
});
if (!ok) return;
} else if (typeof confirm === 'function' && !confirm(confirmPrompt)) {
return;
}
}
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ||
@@ -381,7 +396,9 @@ function triggerLogExport(exportType = 'auto') {
if (exportType === 'selected') {
if (ids.length === 0) {
alert('请先勾选需要导出的日志条目!');
if (window.showToast) {
window.showToast('请先勾选需要导出的日志条目!', 'warning');
}
return;
}
urlParams.set('ids', ids.join(','));
@@ -402,7 +419,9 @@ function openBatchModal(modalId, tableId) {
if (!m) return;
const checked = document.querySelectorAll(`#${tableId} .row-checkbox:checked`);
if (checked.length === 0) {
alert('请先勾选需要批量操作的项!');
if (window.showToast) {
window.showToast('请先勾选需要批量操作的项!', 'warning');
}
return;
}
m.style.display = 'flex';
@@ -430,7 +449,9 @@ function submitBatchUserCredits() {
function submitBatchUserExpires() {
const expires = document.getElementById('batch-expires-date')?.value || '';
if (!expires) {
alert('请选择到期日期!');
if (window.showToast) {
window.showToast('请选择到期日期!', 'warning');
}
return;
}
executeBatchAction('users-table', '/admin/users/batch', 'set_expires', { expires_at: expires });
@@ -451,3 +472,182 @@ function submitBatchPlatformQps() {
executeBatchAction('platforms-table', '/admin/platforms/batch', 'set_qps', { qps_limit: qps });
}
/**
* ==========================================================================
* 轻量级网页自定义下拉菜单组件 (替代系统原生 <select> 灰色弹窗)
* ==========================================================================
*/
function initCustomSelects() {
document.querySelectorAll('select:not(.native-select)').forEach(sel => {
if (sel.dataset.customSelectInit === 'true') return;
sel.dataset.customSelectInit = 'true';
sel.style.display = 'none';
const wrap = document.createElement('div');
wrap.className = 'custom-select-wrap';
if (sel.className) {
sel.className.split(/\s+/).forEach(c => {
if (c) wrap.classList.add(c + '-wrap');
});
}
if (sel.id) wrap.id = sel.id + '-custom-wrap';
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'custom-select-btn';
const btnText = document.createElement('span');
btnText.className = 'custom-select-btn-text';
const chevron = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
chevron.setAttribute('class', 'custom-select-chevron');
chevron.setAttribute('width', '11');
chevron.setAttribute('height', '11');
chevron.setAttribute('viewBox', '0 0 24 24');
chevron.setAttribute('fill', 'none');
chevron.setAttribute('stroke', 'currentColor');
chevron.setAttribute('stroke-width', '2.5');
chevron.setAttribute('stroke-linecap', 'round');
chevron.setAttribute('stroke-linejoin', 'round');
chevron.innerHTML = '<polyline points="6 9 12 15 18 9"></polyline>';
btn.appendChild(btnText);
btn.appendChild(chevron);
wrap.appendChild(btn);
const popover = document.createElement('div');
popover.className = 'custom-select-popover';
function updateOptions() {
popover.innerHTML = '';
const currVal = sel.value;
let foundText = '';
Array.from(sel.children).forEach(child => {
if (child.tagName === 'OPTGROUP') {
const header = document.createElement('div');
header.className = 'custom-select-group-header';
header.textContent = child.label || '';
popover.appendChild(header);
Array.from(child.children).forEach(opt => {
const item = renderItem(opt, currVal);
if (opt.value === currVal || opt.selected) foundText = opt.text;
popover.appendChild(item);
});
} else if (child.tagName === 'OPTION') {
const item = renderItem(child, currVal);
if (child.value === currVal || child.selected) foundText = child.text;
popover.appendChild(item);
}
});
const activeOpt = sel.options[sel.selectedIndex];
btnText.textContent = foundText || (activeOpt ? activeOpt.text : '') || '请选择';
}
function renderItem(opt, currVal) {
const item = document.createElement('button');
item.type = 'button';
item.className = 'custom-select-item' + (opt.value === currVal ? ' active' : '');
item.dataset.value = opt.value;
const t = document.createElement('span');
t.className = 'custom-select-item-text';
t.textContent = opt.text;
const chk = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
chk.setAttribute('class', 'custom-select-item-check');
chk.setAttribute('width', '13');
chk.setAttribute('height', '13');
chk.setAttribute('viewBox', '0 0 24 24');
chk.setAttribute('fill', 'none');
chk.setAttribute('stroke', 'currentColor');
chk.setAttribute('stroke-width', '2.5');
chk.setAttribute('stroke-linecap', 'round');
chk.setAttribute('stroke-linejoin', 'round');
chk.innerHTML = '<polyline points="20 6 9 17 4 12"></polyline>';
item.appendChild(t);
item.appendChild(chk);
item.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
sel.value = opt.value;
btnText.textContent = opt.text;
wrap.classList.remove('open');
popover.querySelectorAll('.custom-select-item').forEach(el => {
if (el.dataset.value === opt.value) el.classList.add('active');
else el.classList.remove('active');
});
sel.dispatchEvent(new Event('change', { bubbles: true }));
if (typeof sel.onchange === 'function') {
sel.onchange.call(sel, new Event('change'));
}
};
return item;
}
updateOptions();
btn.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
const isOpen = wrap.classList.contains('open');
document.querySelectorAll('.custom-select-wrap.open').forEach(w => {
if (w !== wrap) w.classList.remove('open');
});
if (!isOpen) {
const rect = btn.getBoundingClientRect();
const spaceBelow = window.innerHeight - rect.bottom;
const spaceAbove = rect.top;
if (spaceBelow < 200 && spaceAbove > spaceBelow) {
wrap.classList.add('drop-up');
} else {
wrap.classList.remove('drop-up');
}
wrap.classList.add('open');
} else {
wrap.classList.remove('open');
}
};
sel.addEventListener('change', () => {
const activeOpt = sel.options[sel.selectedIndex];
if (activeOpt) {
btnText.textContent = activeOpt.text;
popover.querySelectorAll('.custom-select-item').forEach(el => {
if (el.dataset.value === sel.value) el.classList.add('active');
else el.classList.remove('active');
});
}
});
wrap.appendChild(popover);
sel.parentNode.insertBefore(wrap, sel.nextSibling);
});
}
document.addEventListener('click', (e) => {
if (!e.target.closest('.custom-select-wrap')) {
document.querySelectorAll('.custom-select-wrap.open').forEach(w => {
w.classList.remove('open');
});
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
document.querySelectorAll('.custom-select-wrap.open').forEach(w => {
w.classList.remove('open');
});
}
});
window.initCustomSelects = initCustomSelects;
+2 -2
View File
@@ -130,7 +130,7 @@
<td style="white-space:nowrap">
<div style="display:flex;flex-direction:column;gap:3px;align-items:flex-start">
<strong style="color:var(--ink)">{{ key['username'] }}</strong>
<span class="badge {{ 'brand' if key['user_role'] == 'admin' else '' }}" style="font-size:10.5px;padding:0 5px;line-height:16px">
<span class="badge {{ 'brand' if key['user_role'] == 'admin' else 'neutral' }}" style="font-size:10.5px;padding:0 5px;line-height:16px">
{{ '管理员' if key['user_role'] == 'admin' else '客户' }}
</span>
</div>
@@ -200,7 +200,7 @@
<button type="button" class="batch-btn batch-btn-primary" onclick="executeBatchAction('keys-table', '/admin/keys/batch', 'enable')">批量启用</button>
<button type="button" class="batch-btn" onclick="executeBatchAction('keys-table', '/admin/keys/batch', 'disable')">批量停用</button>
<button type="button" class="batch-btn" onclick="openBatchModal('batch-key-qps-modal', 'keys-table')">覆盖 QPS</button>
<button type="button" class="batch-btn batch-btn-danger" onclick="executeBatchAction('keys-table', '/admin/keys/batch', 'delete', {}, '确定要彻底删除选中的 API Key 吗?此操作无法恢复!')">删除 Key</button>
<button type="button" class="batch-btn batch-btn-danger" onclick="executeBatchAction('keys-table', '/admin/keys/batch', 'delete', {}, '确定要彻底删除选中的 API Key 吗?此操作无法恢复!', '删除密钥确认', 'danger')">删除 Key</button>
<div class="batch-toolbar-divider"></div>
<button type="button" class="batch-btn batch-btn-clear" onclick="clearTableSelection('keys-table')" title="取消选择">&times; 清空</button>
</div>
+4 -11
View File
@@ -73,7 +73,6 @@
<th class="th-sortable" onclick="handleSort('logs', 'duration_ms')" style="white-space:nowrap;width:85px;text-align:right">
耗时 <span class="sort-icon {{ 'active' if logs_table.sorting.sort_by=='duration_ms' }}">{{ '↑' if logs_table.sorting.sort_by=='duration_ms' and logs_table.sorting.order=='asc' else ('↓' if logs_table.sorting.sort_by=='duration_ms' else '↕') }}</span>
</th>
<th class="th-action" style="width:70px">操作</th>
</tr>
</thead>
<tbody>
@@ -107,20 +106,14 @@
<td style="white-space:nowrap;text-align:center"><span class="badge {{ '' if log['status_code']<400 else 'off' }}">{{ log['status_code'] }}</span></td>
<td style="white-space:nowrap">
{% if log['error_code'] %}
<code style="font-size:12px;font-weight:600;color:#dc2626;background:#fef2f2;padding:2px 6px;border-radius:4px;border:1px solid #fee2e2">{{ log['error_code'] }}</code>
{% else %}-{% endif %}
<code class="error-code-badge">{{ log['error_code'] }}</code>
{% else %}<span class="muted">-</span>{% endif %}
</td>
<td style="white-space:nowrap;text-align:right;font-variant-numeric:tabular-nums">{{ log['duration_ms'] }} ms</td>
<td class="td-action" style="white-space:nowrap;text-align:right">
<form method="post" action="{{ url_for('admin.delete_log', log_id=log['id']) }}" onsubmit="return confirm('确定要删除该条日志记录吗?')" style="display:inline;margin:0">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-danger btn-small" style="padding:0 9px;height:28px" title="删除该条日志">删除</button>
</form>
</td>
</tr>
{% else %}
<tr>
<td colspan="10" class="muted" style="text-align:center">暂无符合条件的日志记录</td>
<td colspan="9" class="muted" style="text-align:center">暂无符合条件的日志记录</td>
</tr>
{% endfor %}
</tbody>
@@ -154,7 +147,7 @@
</div>
<div class="batch-toolbar-divider"></div>
<button type="button" class="batch-btn batch-btn-primary" onclick="triggerLogExport('selected')">批量导出 CSV</button>
<button type="button" class="batch-btn batch-btn-danger" onclick="executeBatchAction('logs-table', '/admin/logs/batch', 'delete', {}, '确定要删除选中的日志记录吗?')">批量删除</button>
<button type="button" class="batch-btn batch-btn-danger" onclick="executeBatchAction('logs-table', '/admin/logs/batch', 'delete', {}, '确定要删除选中的日志记录吗?此操作无法恢复。', '删除日志确认', 'danger')">批量删除</button>
<div class="batch-toolbar-divider"></div>
<button type="button" class="batch-btn batch-btn-clear" onclick="clearTableSelection('logs-table')" title="取消选择">&times; 清空</button>
</div>
+1 -1
View File
@@ -9,7 +9,7 @@
<h1>系统管理概览</h1>
<div class="muted">控制服务全局开放状态、配置客户到期时间与各平台 QPS 限制。</div>
</div>
<span class="badge">超级管理员</span>
<span class="badge brand">超级管理员</span>
</div>
<div class="stats">
<div class="card stat">
+6 -6
View File
@@ -174,18 +174,18 @@
onchange="triggerSettingsSubmit(this)">
</div>
<div class="api-tip-preview-box">
<div class="api-tip-preview-header">
<details class="api-tip-preview-box" style="cursor:pointer">
<summary class="api-tip-preview-header" style="user-select:none;outline:none">
<span class="api-tip-preview-title">
<svg class="app-icon" style="width:13px;height:13px" aria-hidden="true">
<use href="{{ url_for('static', filename='icons.svg') }}#icon-code"></use>
</svg>
响应 JSON 效果预览
</span>
<span class="api-tip-preview-badge">实时联动</span>
</div>
<pre class="api-tip-code"><code id="api-tip-preview-code"></code></pre>
</div>
<span class="muted" style="font-size:12px">点击展开/收起 ▾</span>
</summary>
<pre class="api-tip-code" style="margin-top:8px;cursor:auto"><code id="api-tip-preview-code"></code></pre>
</details>
</div>
</div>
</section>
+1 -1
View File
@@ -85,7 +85,7 @@
<td style="text-align:center"><input type="checkbox" class="row-checkbox" value="{{ user['id'] }}"></td>
<td style="font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px;color:var(--ink-muted);font-weight:500">#{{ user['id'] }}</td>
<td style="white-space:nowrap"><strong style="color:var(--ink)">{{ user['username'] }}</strong></td>
<td style="white-space:nowrap;text-align:center"><span class="badge {{ 'brand' if user['role']=='admin' else '' }}">{{ '管理员' if user['role']=='admin' else '客户' }}</span></td>
<td style="white-space:nowrap;text-align:center"><span class="badge {{ 'brand' if user['role']=='admin' else 'neutral' }}">{{ '管理员' if user['role']=='admin' else '客户' }}</span></td>
<td style="white-space:nowrap;text-align:center">
<span class="badge {{ '' if user['active'] else 'off' }}">{{ '正常' if user['active'] else '停用' }}</span>
</td>
+117 -45
View File
@@ -345,7 +345,7 @@
<div class="pg-section-label">
<span>待解析链接 / 分享文案 <span style="color:#ef4444">*</span></span>
</div>
<textarea id="pg-target-url" class="pg-input" rows="3"
<textarea id="pg-target-url" class="pg-input" rows="4"
placeholder="粘贴目标作品分享链接或文案 (例如 https://v.douyin.com/...)"
required autocomplete="off" oninput="syncCodeSnippets()"></textarea>
</div>
@@ -377,17 +377,39 @@
onkeydown="handleKeyInputKeydown(event)">
</div>
<select id="pg-key-selector" class="pg-key-dropdown" onchange="handleApiKeyDropdownChange(this)" title="选择已有 Key 或前往创建">
<option value="">未选择 Key</option>
{% if available_keys and available_keys|length > 0 %}
{% for k in available_keys %}
<option value="{{ k['key_prefix'] }}..." data-name="{{ k['name'] or '密钥' }}" {% if (new_api_key and k['key_prefix'] in new_api_key) or (not new_api_key and loop.first) %}selected{% endif %}>{{ k['name'] or '密钥' }}</option>
{% endfor %}
<option value="__GO_CREATE_KEY__">+ 创建新 Key / 管理密钥 ↗</option>
{% else %}
<option value="__GO_CREATE_KEY__">+ 暂无 Key,点击前往创建 ↗</option>
{% endif %}
</select>
<!-- Custom Dropdown Component for Playground Key Selection -->
<div class="pg-key-dropdown-wrap" id="pg-key-dropdown-wrap">
<button type="button" class="pg-key-dropdown-trigger" id="pg-key-dropdown-btn" onclick="togglePgKeyDropdown(event)" title="选择已有 Key 或前往创建">
<span id="pg-key-dropdown-label">{{ first_key['name'] if has_initial_key else '选择 Key' }}</span>
<svg class="pg-key-dropdown-chevron" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div class="pg-key-dropdown-menu" id="pg-key-dropdown-menu">
<button type="button" class="pg-key-menu-item {% if not has_initial_key and not new_api_key %}active{% endif %}" data-val="" onclick="handlePgKeyItemSelect('', '手动输入')">
<span class="pg-key-item-title">未选择 Key</span>
<svg class="pg-key-item-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
</button>
{% if available_keys and available_keys|length > 0 %}
{% for k in available_keys %}
{% set is_selected = (new_api_key and k['key_prefix'] in new_api_key) or (not new_api_key and loop.first) %}
<button type="button" class="pg-key-menu-item {% if is_selected %}active{% endif %}" data-val="{{ k['key_prefix'] }}..." data-name="{{ k['name'] or '密钥' }}" onclick="handlePgKeyItemSelect('{{ k['key_prefix'] }}...', '{{ k['name'] or '密钥' }}')">
<span class="pg-key-item-title">{{ k['name'] or '密钥' }}</span>
<svg class="pg-key-item-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
</button>
{% endfor %}
<div class="pg-key-menu-divider"></div>
<button type="button" class="pg-key-menu-item action-create" onclick="handlePgKeyActionCreate()">
<span>+ 创建新 Key / 管理密钥 ↗</span>
</button>
{% else %}
<div class="pg-key-menu-divider"></div>
<button type="button" class="pg-key-menu-item action-create" onclick="handlePgKeyActionCreate()">
<span>+ 暂无 Key,点击前往创建 ↗</span>
</button>
{% endif %}
</div>
</div>
</div>
</div>
@@ -601,30 +623,44 @@
if (input && input.style.display !== 'none') input.focus();
};
window.handleApiKeyDropdownChange = function(sel) {
const val = typeof sel === 'string' ? sel : (sel ? sel.value : '');
if (val === '__GO_CREATE_KEY__') {
const dropdown = document.getElementById('pg-key-selector');
if (dropdown) dropdown.value = '';
goToKeyManagement();
return;
window.togglePgKeyDropdown = function(e) {
if (e) {
e.preventDefault();
e.stopPropagation();
}
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap) {
wrap.classList.toggle('open');
}
};
window.closePgKeyDropdown = function() {
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap) {
wrap.classList.remove('open');
}
};
window.handlePgKeyItemSelect = function(val, name) {
closePgKeyDropdown();
if (!val) {
clearSelectedKey();
return;
}
const dropdown = document.getElementById('pg-key-selector');
const opt = dropdown ? dropdown.options[dropdown.selectedIndex] : null;
const name = opt ? (opt.dataset.name || opt.text) : '密钥';
applySelectedKey(val, name);
};
window.handlePgKeyActionCreate = function() {
closePgKeyDropdown();
goToKeyManagement();
};
window.applySelectedKey = function(prefixVal, name) {
const chip = document.getElementById('pg-selected-key-chip');
const chipName = document.getElementById('pg-key-chip-name');
const chipPrefix = document.getElementById('pg-key-chip-prefix');
const input = document.getElementById('pg-api-key');
const dropdown = document.getElementById('pg-key-selector');
const label = document.getElementById('pg-key-dropdown-label');
if (chipName) chipName.textContent = name || '密钥';
if (chipPrefix) chipPrefix.textContent = '(' + prefixVal + ')';
@@ -638,10 +674,18 @@
input.style.display = 'none';
}
if (dropdown && dropdown.value !== prefixVal) {
dropdown.value = prefixVal;
if (label) {
label.textContent = name || '密钥';
}
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => {
if (item.dataset.val === prefixVal) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
syncCodeSnippets();
};
@@ -649,7 +693,7 @@
if (e) e.stopPropagation();
const chip = document.getElementById('pg-selected-key-chip');
const input = document.getElementById('pg-api-key');
const dropdown = document.getElementById('pg-key-selector');
const label = document.getElementById('pg-key-dropdown-label');
if (chip) {
chip.style.display = 'none';
@@ -661,24 +705,39 @@
input.placeholder = '请输入或选择 API Key';
input.focus();
}
if (dropdown) {
dropdown.value = '';
if (label) {
label.textContent = '选择 Key';
}
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => {
if (!item.dataset.val) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
syncCodeSnippets();
};
window.handleManualKeyInput = function() {
const chip = document.getElementById('pg-selected-key-chip');
const input = document.getElementById('pg-api-key');
const dropdown = document.getElementById('pg-key-selector');
const label = document.getElementById('pg-key-dropdown-label');
if (chip && chip.style.display !== 'none') {
chip.style.display = 'none';
chip.dataset.val = '';
}
if (dropdown) {
dropdown.value = '';
if (label) {
label.textContent = '选择 Key';
}
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => {
if (!item.dataset.val) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
syncCodeSnippets();
};
@@ -691,23 +750,36 @@
};
window.selectApiKey = function(keyVal) {
const dropdown = document.getElementById('pg-key-selector');
if (dropdown) {
for (let i = 0; i < dropdown.options.length; i++) {
if (dropdown.options[i].value === keyVal) {
dropdown.selectedIndex = i;
applySelectedKey(keyVal, dropdown.options[i].dataset.name || dropdown.options[i].text);
return;
}
let matched = false;
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item[data-val]').forEach(item => {
if (item.dataset.val === keyVal || item.dataset.val === (keyVal + '...')) {
applySelectedKey(item.dataset.val, item.dataset.name || '密钥');
matched = true;
}
});
if (!matched) {
const input = document.getElementById('pg-api-key');
if (input) {
input.value = keyVal;
syncCodeSnippets();
}
}
const input = document.getElementById('pg-api-key');
if (input) {
input.value = keyVal;
syncCodeSnippets();
}
};
document.addEventListener('click', function(e) {
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap && wrap.classList.contains('open') && !wrap.contains(e.target)) {
wrap.classList.remove('open');
}
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap) wrap.classList.remove('open');
}
});
window.resetPlayground = function() {
const urlInput = document.getElementById('pg-target-url');
if (urlInput) urlInput.value = '';
+1 -1
View File
@@ -188,7 +188,7 @@
<div class="batch-toolbar-divider"></div>
<button type="button" class="batch-btn batch-btn-primary" onclick="executeBatchAction('keys-table', '/console/keys/batch', 'enable')">批量启用</button>
<button type="button" class="batch-btn" onclick="executeBatchAction('keys-table', '/console/keys/batch', 'disable')">批量停用</button>
<button type="button" class="batch-btn batch-btn-danger" onclick="executeBatchAction('keys-table', '/console/keys/batch', 'delete', {}, '确定要彻底删除选中的 API Key 吗?此操作无法恢复!')">删除 Key</button>
<button type="button" class="batch-btn batch-btn-danger" onclick="executeBatchAction('keys-table', '/console/keys/batch', 'delete', {}, '确定要彻底删除选中的 API Key 吗?此操作无法恢复!', '删除密钥确认', 'danger')">删除 Key</button>
<div class="batch-toolbar-divider"></div>
<button type="button" class="batch-btn batch-btn-clear" onclick="clearTableSelection('keys-table')" title="取消选择">&times; 清空</button>
</div>
+2 -2
View File
@@ -94,8 +94,8 @@
<td style="white-space:nowrap;text-align:center"><span class="badge {{ '' if log['status_code']<400 else 'off' }}">{{ log['status_code'] }}</span></td>
<td style="white-space:nowrap">
{% if log['error_code'] %}
<code style="font-size:12px;font-weight:600;color:#dc2626;background:#fef2f2;padding:2px 6px;border-radius:4px;border:1px solid #fee2e2">{{ log['error_code'] }}</code>
{% else %}-{% endif %}
<code class="error-code-badge">{{ log['error_code'] }}</code>
{% else %}<span class="muted">-</span>{% endif %}
</td>
<td style="white-space:nowrap;text-align:right;font-variant-numeric:tabular-nums">{{ log['duration_ms'] }} ms</td>
</tr>
+11
View File
@@ -376,11 +376,22 @@ class ManagementTest(unittest.TestCase):
response = self.client.get("/admin/logs/export.csv")
self.assertEqual(response.status_code, 200)
self.assertIn("text/csv", response.content_type)
self.assertIn("Content-Length", response.headers)
body = response.get_data(as_text=True)
self.assertIn("请求 URL", body)
self.assertIn("https://example.com/video/1", body)
self.assertIn("MEDIA_NOT_FOUND", body)
# Test with error status filter and all mode
filtered_resp = self.client.get("/admin/logs/export.csv?logs_status=error&export_type=all")
self.assertEqual(filtered_resp.status_code, 200)
self.assertIn("https://example.com/video/1", filtered_resp.get_data(as_text=True))
# Test with 200 status filter (should exclude error log)
ok_resp = self.client.get("/admin/logs/export.csv?logs_status=200&export_type=all")
self.assertEqual(ok_resp.status_code, 200)
self.assertNotIn("https://example.com/video/1", ok_resp.get_data(as_text=True))
def test_user_can_export_only_own_logs_as_csv(self):
self.client.post(
"/auth/register",