This repository has been archived on 2026-10-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
NeteaseUrl/core/http_errors.py
T
snowy-yang 65adfc9089 refactor: 删除 aiohttp_compat 垫片,music_api 改走原生 core.http_client
core/aiohttp_compat 是「同步转异步」迁移期的 requests 同形异步垫片:它存在的
唯一理由是让既有 `requests.post/get + raise_for_status()` 风格的代码以最小
改动迁到异步。其两个调用方(music_api/api.py、music_api/client.py)**本就已是
async def**——垫片只剩「保留 requests 语义」这一层包装,属于迁移残留。

改动:
- api.py:23 处 requests.post/get → await core.http_client.request()。
  该文件每处都在请求后立刻 raise_for_status() 才取 .json(),从不把 4xx 当数据读,
  故「_once 对非 2xx 直接抛 UpstreamHTTPError」与旧语义等价(原 raise_for_status
  抛的 HTTPError 也一律落入 RequestException 分支);
  except requests.RequestException → except UpstreamError。
- client.py:两个自管重试的方法改用新公开的 core.http_client.request_once()
  (单次、不重试),保留原有「5xx 退避重试一次 / 4xx 立即失败」的分流——
  把 status_code>=500 的判断换成 UpstreamHTTPError.status,行为逐条对齐
  (4xx=风控不重试,网络/5xx 重试一次)。响应体上限交由客户端 max_bytes 统一把关。
  post_request_full 返回类型改为 HTTPResult(qr.py 用到的 .text/.cookies/.headers
  三者在 HTTPResult 上齐备)。
- core/http_client:_once 更名并公开为 request_once(自管重试的调用方需要它)。
  注:这是为「删垫片」而补的唯一一个小口子,不是新增抽象。

注意一处**有意的行为变化**:api.py 原经垫片请求零重试,现在 request() 自带
「网络异常/5xx 退避重试一次、4xx 不重试」(core.http_client 既定口径)。
429/460 属 4xx 不重试,不加剧风控。

- 删除 core/aiohttp_compat.py;web/app.py 去掉其 close();pyproject 去掉其
  per-file-ignore;core/http_errors.py 注释更正为「仅供 core.sync_http」。
- 测试:test_aiohttp_compat.py 拆解为 test_async_bridge.py(只留桥的两条契约,
  垫片自身的 4 条随垫片消亡);test_search_music / test_playlist_detail 的替身
  边界从 api.requests.post 换成 api._http.request,异常类型换成 UpstreamNetworkError。

门禁:ruff 全过 / pyright 0-0 / pytest 383 项全绿(0 失败;383=387-6+2,账面吻合)。
2026-09-28 19:17:03 +08:00

41 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""requests 同形异常层次(同步 HTTP 门面 core.sync_http 使用)。
历史:`core.aiohttp_compat`(异步垫片)与 `core.sync_http`(同步门面)曾各自
定义一份 `RequestException` / `HTTPError`——两份定义互不相干,于是同一条调用链上
「同步段抛的异常捕获不到异步段的同类失败」。异步垫片已删除、其调用方(music_api)
全面改走 core.http_client(自带 UpstreamError 层次);此处保留唯一来源,
供仍在线程里同步取数据的 core.sync_http 使用。
命名沿用 requests(`Timeout` / `ConnectionError` 与内置异常同名,这是 requests
自身的约定——调用方应带模块前缀引用,例如 `requests.ConnectionError`,
裸 `ConnectionError` 会命中内置的那个)。
层次:
RequestException 网络 / 协议层失败(可捕获的总入口)
├── HTTPError raise_for_status() 抛出的状态异常(携带 response)
├── Timeout 请求超时
└── ConnectionError 连接错误
"""
from typing import Any
class RequestException(Exception):
"""请求异常基类(网络/协议层)。"""
class HTTPError(RequestException):
"""raise_for_status() 抛出的 HTTP 状态异常。"""
def __init__(self, message: str, response: Any = None):
super().__init__(message)
self.response = response
class Timeout(RequestException):
"""请求超时。"""
class ConnectionError(RequestException):
"""连接错误。"""