Files
ViGent2/Docs/DevLogs/Day9.md
Kevin Wong 561d74e16d 更新
2026-01-23 10:07:35 +08:00

3.4 KiB
Raw Blame History

Day 9: 发布模块代码优化

日期: 2026-01-23
目标: 代码质量优化 + 发布功能验证


📋 任务概览

任务 状态
B站/抖音发布验证 完成
资源清理保障 (try-finally) 完成
超时保护 (消除无限循环) 完成
小红书 headless 模式修复 完成
API 输入验证 完成
类型提示完善 完成
服务层代码优化 完成

🎉 发布验证结果

登录功能

  • B站登录成功 - 策略3(Text)匹配Cookie已保存
  • 抖音登录成功 - 策略3(Text)匹配Cookie已保存

发布功能

  • 抖音发布成功 - 自动关闭弹窗、跳转管理页面
  • B站发布成功 - API返回 bvid: BV14izPBQEbd

🔧 代码优化

1. 资源清理保障

问题Playwright 浏览器在异常路径可能未关闭

修复try-finally 模式确保资源释放

browser = None
context = None
try:
    browser = await playwright.chromium.launch(headless=True)
    context = await browser.new_context(...)
    # ... 业务逻辑 ...
finally:
    if context:
        try: await context.close()
        except Exception: pass
    if browser:
        try: await browser.close()
        except Exception: pass

2. 超时保护

问题while True 循环可能导致任务卡死

修复:添加类级别超时常量

class DouyinUploader(BaseUploader):
    UPLOAD_TIMEOUT = 300       # 视频上传超时
    PUBLISH_TIMEOUT = 180      # 发布检测超时
    PAGE_REDIRECT_TIMEOUT = 60 # 页面跳转超时

3. B站 bvid 提取修复

问题API 返回的 bvid 在 data 字段内

修复:同时检查多个位置

bvid = ret.get('data', {}).get('bvid') or ret.get('bvid', '')
aid = ret.get('data', {}).get('aid') or ret.get('aid', '')

4. API 输入验证

修复:所有端点添加平台验证

SUPPORTED_PLATFORMS = {"bilibili", "douyin", "xiaohongshu"}

if platform not in SUPPORTED_PLATFORMS:
    raise HTTPException(status_code=400, detail=f"不支持的平台: {platform}")

📁 修改文件列表

后端

文件 修改内容
app/api/publish.py 输入验证、平台常量、文档改进
app/services/publish_service.py 类型提示、平台 enabled 标记
app/services/qr_login_service.py 类型提示、修复裸 except、超时常量
app/services/uploader/base_uploader.py 类型提示
app/services/uploader/bilibili_uploader.py bvid提取修复、类型提示
app/services/uploader/douyin_uploader.py 资源清理、超时保护、类型提示
app/services/uploader/xiaohongshu_uploader.py headless模式、资源清理、超时保护

完成总结

  1. 发布功能验证通过 - B站/抖音登录和发布均正常
  2. 代码健壮性提升 - 资源清理、超时保护、异常处理
  3. 代码可维护性 - 完整类型提示、常量化配置
  4. 服务器兼容性 - 小红书 headless 模式修复

🔗 相关文档