refactor(async): music_api 异步化 + 全项目 lint 收敛

music_api.py:
- 22 个方法改 async(HTTPClient.post_request*/NeteaseAPI.*/QRLoginManager.*),
  33 处 requests.* → await core.aiohttp_compat.*
- 16 个模块级同步包装改走 run_sync 桥(main.py 等 99 个同步调用点零改动)
- async 内 time.sleep → asyncio.sleep(修 7 处阻塞事件循环)

musica_downloader/qr_login:
- 单曲三请求 ThreadPoolExecutor → asyncio.gather(语义等价,失败处理保留)
- interactive_login 改 async,CLI 入口用 asyncio.run

真实缺陷修复(lint 发现):
- podcast_api._to_int 未定义(2 处调用会 NameError)→ 补安全转换 helper
- main.py VALID_QUALITY_LEVELS 重复定义(覆盖 core.config 导入值)→ 移除
- 移除死代码变量(salt×2/device_id×3/file_path/zipped_files)

lint 收敛:524→0(ruff All checks passed);pyright 0 errors。
pyproject 记录「有意保留」项(B904/RUF012/S305 上游协议等)及理由。

验证:冒烟 10/10;pytest 16/16;真实上游 get_toplist 异步直调与桥接均得 63 条。
This commit is contained in:
snowy-yang committed 2026-09-26 00:32:45 +08:00
1 parent 4962542e78
commit ce7ea66d6a
8 files changed
+520 -490

No files matched your search

+21 -24
View File
@@ -6,12 +6,9 @@
import hmac
import secrets
import sqlite3
import time
from typing import Optional, Tuple
from flask import request, send_file
import auth_system as auth
@@ -304,7 +301,7 @@ def register_auth_routes(app) -> None:
return _ok({'user': auth._user_public(fresh),
'duration_text': auth.format_credits(fresh['duration_seconds']),
'redirect': 'admin' if fresh['role'] == 'admin' else 'user'},
f'注册成功' + (f',已赠送 {credits} 次下载次数' if credits else ''))
'注册成功' + (f',已赠送 {credits} 次下载次数' if credits else ''))
except Exception:
return _err('注册失败,请稍后重试', 500)
@@ -366,7 +363,7 @@ def register_auth_routes(app) -> None:
'密码验证通过,请完成邮箱验证')
auth.login_session(user)
# IP 归属地异常检测:24h 内 >=3 个不同省份自动封禁(防倒卖)
banned, info = auth.record_login_location(user, auth._client_ip())
banned, _info = auth.record_login_location(user, auth._client_ip())
if banned:
auth.logout_session()
return _err('检测到账号在多个省份异常登录,已自动封禁,请联系管理员')
@@ -442,7 +439,7 @@ def register_auth_routes(app) -> None:
return _err('账号已被禁用,请联系管理员')
auth.login_session(user)
# IP 归属地异常检测:管理员天然豁免省份封禁(record_login_location 内部判定)
banned, info = auth.record_login_location(user, auth._client_ip())
banned, _info = auth.record_login_location(user, auth._client_ip())
if banned:
auth.logout_session()
return _err('检测到账号在多个省份异常登录,已自动封禁,请联系管理员')
@@ -552,7 +549,7 @@ def register_auth_routes(app) -> None:
auth.add_log('success', _actor(), auth._client_ip(), '删除用户', target['username'] if target else str(uid))
return _ok(message='用户已删除')
except Exception as e:
return _err(f'删除失败: {str(e)}', 500)
return _err(f'删除失败: {e!s}', 500)
@app.route('/admin/site/user/duration', methods=['POST'])
@auth.admin_required
@@ -576,9 +573,9 @@ def register_auth_routes(app) -> None:
f'{target["username"]} → {count} 次')
return _ok(message=f'已修改为 {count} 次')
except Exception as e:
return _err(f'修改失败: {str(e)}', 500)
return _err(f'修改失败: {e!s}', 500)
def _block_admin_target(target) -> Optional[Tuple]:
def _block_admin_target(target) -> tuple | None:
"""禁止对管理员账号执行危险操作(防自锁)"""
if target and target['role'] == 'admin':
return _err('不能对管理员账号执行该操作')
@@ -622,7 +619,7 @@ def register_auth_routes(app) -> None:
f'{username} · {credits} 次')
return _ok(message=f'用户 {username} 创建成功({credits} 次)')
except Exception as e:
return _err(f'创建失败: {str(e)}', 500)
return _err(f'创建失败: {e!s}', 500)
@app.route('/admin/site/user/reset_password', methods=['POST'])
@auth.admin_required
@@ -653,7 +650,7 @@ def register_auth_routes(app) -> None:
auth.add_log('success', _actor(), auth._client_ip(), '重置密码', target['username'])
return _ok(message=f'已重置 {target["username"]} 的密码')
except Exception as e:
return _err(f'重置失败: {str(e)}', 500)
return _err(f'重置失败: {e!s}', 500)
@app.route('/admin/site/user/toggle', methods=['POST'])
@auth.admin_required
@@ -674,7 +671,7 @@ def register_auth_routes(app) -> None:
return _ok({'status': new_status},
message=f'已{"启用" if new_status else "禁用"} {target["username"]}')
except Exception as e:
return _err(f'操作失败: {str(e)}', 500)
return _err(f'操作失败: {e!s}', 500)
@app.route('/admin/site/user/ban', methods=['POST'])
@auth.admin_required
@@ -704,7 +701,7 @@ def register_auth_routes(app) -> None:
auth._client_ip(), '解封用户', row['username'])
return _ok(message=f'已解封用户「{row["username"]}」')
except Exception as e:
return _err(f'操作失败: {str(e)}', 500)
return _err(f'操作失败: {e!s}', 500)
@app.route('/admin/site/user/cookie', methods=['POST'])
@auth.admin_required
@@ -743,7 +740,7 @@ def register_auth_routes(app) -> None:
auth.add_log('success', _actor(), auth._client_ip(), '保存SMTP配置', f'{host}:{port}')
return _ok(message='SMTP 配置已保存')
except Exception as e:
return _err(f'保存失败: {str(e)}', 500)
return _err(f'保存失败: {e!s}', 500)
@app.route('/admin/site/smtp/test', methods=['POST'])
@auth.admin_required
@@ -762,7 +759,7 @@ def register_auth_routes(app) -> None:
return _ok(message='测试邮件已发送,请查收')
except Exception as e:
auth.add_log('fail', _actor(), auth._client_ip(), 'SMTP测试', str(e))
return _err(f'发送失败: {str(e)}', 500)
return _err(f'发送失败: {e!s}', 500)
@app.route('/admin/site/logs', methods=['POST'])
@auth.admin_required
@@ -815,7 +812,7 @@ def register_auth_routes(app) -> None:
return _ok({'codes': codes, 'credits': credits, 'count': len(codes)},
f'已生成 {len(codes)} 张卡密')
except Exception as e:
return _err(f'生成失败: {str(e)}', 500)
return _err(f'生成失败: {e!s}', 500)
@app.route('/admin/site/cards/list', methods=['POST'])
@auth.admin_required
@@ -884,7 +881,7 @@ def register_auth_routes(app) -> None:
auth.add_log('success', _actor(), auth._client_ip(), '保存公告', str(data.get('title') or ''))
return _ok(message='公告已保存')
except Exception as e:
return _err(f'保存失败: {str(e)}', 500)
return _err(f'保存失败: {e!s}', 500)
# -------------------- 播放 API 密钥 --------------------
@@ -917,7 +914,7 @@ def register_auth_routes(app) -> None:
auth.add_log('success', _actor(), auth._client_ip(), '数据库备份', name)
return _ok({'name': name}, f'备份完成:{name}')
except Exception as e:
return _err(f'备份失败: {str(e)}', 500)
return _err(f'备份失败: {e!s}', 500)
@app.route('/admin/site/backup/list', methods=['POST'])
@auth.admin_required
@@ -979,7 +976,7 @@ def register_auth_routes(app) -> None:
dest.unlink()
except Exception:
pass
return _err(f'上传失败: {str(e)}', 500)
return _err(f'上传失败: {e!s}', 500)
@app.route('/admin/site/backup/restore', methods=['POST'])
@auth.admin_required
@@ -992,10 +989,10 @@ def register_auth_routes(app) -> None:
except ValueError as e:
# 第 95 条(P3-1):客户端可纠正错误(备份不存在/校验失败)返回 400,
# 与 delete 的 404 口径对齐——原实现一律 500
return _err(f'恢复失败: {str(e)}', 400)
return _err(f'恢复失败: {e!s}', 400)
except Exception as e:
auth.add_log('fail', _actor(), auth._client_ip(), '恢复数据库', str(e))
return _err(f'恢复失败: {str(e)}', 500)
return _err(f'恢复失败: {e!s}', 500)
@app.route('/admin/site/backup/delete', methods=['POST'])
@auth.admin_required
@@ -1006,7 +1003,7 @@ def register_auth_routes(app) -> None:
return _ok(message='备份已删除')
return _err('备份文件不存在', 404)
except Exception as e:
return _err(f'删除失败: {str(e)}', 500)
return _err(f'删除失败: {e!s}', 500)
@app.route('/admin/site/backup/auto', methods=['POST'])
@auth.admin_required
@@ -1023,10 +1020,10 @@ def register_auth_routes(app) -> None:
if hours < 0:
return _err('间隔不能为负')
auth.set_setting('backup_interval_hours', str(hours))
return _ok(message='定时备份已开启,每 {} 小时自动备份'.format(hours) if hours > 0
return _ok(message=f'定时备份已开启,每 {hours} 小时自动备份' if hours > 0
else '定时备份已关闭')
except Exception as e:
return _err(f'设置失败: {str(e)}', 500)
return _err(f'设置失败: {e!s}', 500)
# ============ 辅助 ============