Archived
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,账面吻合)。
This commit is contained in:
1 parent
b089dadac2
commit
65adfc9089
13 files changed
+139
-348
No files matched your search
@@ -1,142 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""requests 兼容的异步 HTTP 垫片(基于 aiohttp)。
|
||||
|
||||
目的:让既有大量 `requests.post/get + response.json()/raise_for_status()` 风格的
|
||||
代码**以最小改动**迁移到异步——把 `import requests` 换成
|
||||
`from core import aiohttp_compat as requests`,加 `await`、加 `async def` 即可,
|
||||
其余 `.text/.json()/.status_code/.raise_for_status()` 语义保持不变。
|
||||
|
||||
与 requests 的语义对齐点(很关键,不得改动):
|
||||
- 请求本身**不**因 4xx/5xx 抛异常;只有显式 `raise_for_status()` 才抛 `HTTPError`
|
||||
(上游风控 429/460 的重试/不重试判断依赖调用方读取 `status_code`,见 music_api.HTTPClient)。
|
||||
- 网络异常/超时抛 `RequestException`(含 `Timeout`)。
|
||||
- `Response` 一次性读全 body(与 requests 一致),暴露 text/json/content/headers/cookies/url。
|
||||
|
||||
连接按事件循环隔离(见 core.http_client 的同样设计)。
|
||||
"""
|
||||
import asyncio
|
||||
import json as _json
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
|
||||
from core.http_errors import ConnectionError, HTTPError, RequestException, Timeout
|
||||
|
||||
DEFAULT_TIMEOUT = 30
|
||||
DEFAULT_MAX_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
class Response:
|
||||
"""requests.Response 的异步子集:body 已读全,属性同步访问。"""
|
||||
|
||||
def __init__(self, status_code: int, url: str, content: bytes,
|
||||
headers: Mapping[str, str], cookies: Mapping[str, str], reason: str = ''):
|
||||
self.status_code = status_code
|
||||
self.url = url
|
||||
self.content = content
|
||||
self.headers = dict(headers)
|
||||
self.cookies = dict(cookies)
|
||||
self.reason = reason
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self.content.decode('utf-8', errors='replace')
|
||||
|
||||
def json(self, **kw) -> Any:
|
||||
return _json.loads(self.text, **kw)
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
if 400 <= self.status_code:
|
||||
raise HTTPError(f"{self.status_code} {self.reason}".strip(), self)
|
||||
|
||||
|
||||
# ---------- 会话(按 loop 隔离的 aiohttp session) ----------
|
||||
|
||||
|
||||
class _SessionState:
|
||||
def __init__(self):
|
||||
self._sessions: dict[int, aiohttp.ClientSession] = {}
|
||||
self._lock: asyncio.Lock | None = None
|
||||
|
||||
def _get_lock(self) -> asyncio.Lock:
|
||||
if self._lock is None:
|
||||
self._lock = asyncio.Lock()
|
||||
return self._lock
|
||||
|
||||
async def session(self) -> aiohttp.ClientSession:
|
||||
key = id(asyncio.get_running_loop())
|
||||
sess = self._sessions.get(key)
|
||||
if sess is not None and not sess.closed:
|
||||
return sess
|
||||
async with self._get_lock():
|
||||
sess = self._sessions.get(key)
|
||||
if sess is None or sess.closed:
|
||||
sess = aiohttp.ClientSession(
|
||||
connector=aiohttp.TCPConnector(limit=100, limit_per_host=32, ttl_dns_cache=300),
|
||||
)
|
||||
self._sessions[key] = sess
|
||||
return sess
|
||||
|
||||
async def close_all(self) -> None:
|
||||
for sess in self._sessions.values():
|
||||
if not sess.closed:
|
||||
await sess.close()
|
||||
self._sessions.clear()
|
||||
|
||||
|
||||
_state = _SessionState()
|
||||
|
||||
|
||||
async def close() -> None:
|
||||
"""关闭所有连接(应用关闭时调用)。"""
|
||||
await _state.close_all()
|
||||
|
||||
|
||||
async def request(
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
params: Any = None,
|
||||
data: Any = None,
|
||||
json: Any = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
cookies: Mapping[str, str] | None = None,
|
||||
timeout: float | None = DEFAULT_TIMEOUT,
|
||||
allow_redirects: bool = True,
|
||||
max_bytes: int = DEFAULT_MAX_BYTES,
|
||||
) -> Response:
|
||||
"""发起单次异步请求,返回 Response(不因 4xx/5xx 抛异常,同 requests)。"""
|
||||
sess = await _state.session()
|
||||
req_timeout = aiohttp.ClientTimeout(total=timeout) if timeout else None
|
||||
try:
|
||||
async with sess.request(
|
||||
method, url,
|
||||
params=params, data=data, json=json,
|
||||
headers=dict(headers) if headers else None,
|
||||
cookies=dict(cookies) if cookies else None,
|
||||
timeout=req_timeout, allow_redirects=allow_redirects,
|
||||
) as resp:
|
||||
body = await resp.read()
|
||||
if len(body) > max_bytes:
|
||||
raise RequestException(f"响应体超过上限 {max_bytes} 字节")
|
||||
return Response(
|
||||
status_code=resp.status,
|
||||
url=str(resp.url),
|
||||
content=body,
|
||||
headers=dict(resp.headers),
|
||||
cookies={k: v.value for k, v in resp.cookies.items()},
|
||||
reason=resp.reason or '',
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise ConnectionError(str(e)) from e
|
||||
except TimeoutError as e:
|
||||
raise Timeout('请求超时') from e
|
||||
|
||||
|
||||
async def get(url: str, **kw) -> Response:
|
||||
return await request('GET', url, **kw)
|
||||
|
||||
|
||||
async def post(url: str, **kw) -> Response:
|
||||
return await request('POST', url, **kw)
|
||||
+7
-2
@@ -143,7 +143,7 @@ class AsyncHTTPClient:
|
||||
|
||||
# ---------- 底层:单次请求(不重试) ----------
|
||||
|
||||
async def _once(
|
||||
async def request_once(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
@@ -156,6 +156,11 @@ class AsyncHTTPClient:
|
||||
timeout: float | None = None,
|
||||
allow_redirects: bool = True,
|
||||
) -> HTTPResult:
|
||||
"""发起一次请求,**不做重试**(自管重试策略的调用方用这个)。
|
||||
|
||||
非 2xx 一律抛 UpstreamHTTPError(含 5xx)——调用方按 .status 自行决定是否重试。
|
||||
request() 在此基础上叠加「网络异常/5xx 退避重试一次」。
|
||||
"""
|
||||
session = await self._session_for_loop()
|
||||
req_timeout = aiohttp.ClientTimeout(total=timeout) if timeout else None
|
||||
try:
|
||||
@@ -211,7 +216,7 @@ class AsyncHTTPClient:
|
||||
# ---------- 高层 API ----------
|
||||
|
||||
async def request(self, method: str, url: str, **kw) -> HTTPResult:
|
||||
return await self._with_retry(lambda: self._once(method, url, **kw))
|
||||
return await self._with_retry(lambda: self.request_once(method, url, **kw))
|
||||
|
||||
async def get_text(self, url: str, **kw) -> str:
|
||||
return (await self.request('GET', url, **kw)).text
|
||||
|
||||
+9
-7
@@ -1,13 +1,15 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""requests 同形异常层次(同步 / 异步两个 HTTP 垫片共用)。
|
||||
"""requests 同形异常层次(同步 HTTP 门面 core.sync_http 使用)。
|
||||
|
||||
`core.aiohttp_compat`(异步)与 `core.sync_http`(同步)此前各自定义了一份
|
||||
`RequestException` / `HTTPError`——两份定义互不相干,于是同一条调用链上
|
||||
「同步段抛的异常捕获不到异步段的同类失败」,调用方被迫记住自己走的是哪条垫片。
|
||||
历史:`core.aiohttp_compat`(异步垫片)与 `core.sync_http`(同步门面)曾各自
|
||||
定义一份 `RequestException` / `HTTPError`——两份定义互不相干,于是同一条调用链上
|
||||
「同步段抛的异常捕获不到异步段的同类失败」。异步垫片已删除、其调用方(music_api)
|
||||
全面改走 core.http_client(自带 UpstreamError 层次);此处保留唯一来源,
|
||||
供仍在线程里同步取数据的 core.sync_http 使用。
|
||||
|
||||
此处收敛为唯一来源;命名沿用 requests(`Timeout` / `ConnectionError` 与内置
|
||||
异常同名,这是 requests 自身的约定——调用方应带模块前缀引用,例如
|
||||
`requests.ConnectionError`,裸 `ConnectionError` 会命中内置的那个)。
|
||||
命名沿用 requests(`Timeout` / `ConnectionError` 与内置异常同名,这是 requests
|
||||
自身的约定——调用方应带模块前缀引用,例如 `requests.ConnectionError`,
|
||||
裸 `ConnectionError` 会命中内置的那个)。
|
||||
|
||||
层次:
|
||||
RequestException 网络 / 协议层失败(可捕获的总入口)
|
||||
|
||||
+3
-3
@@ -18,9 +18,9 @@ from core import async_bridge
|
||||
from core.http_client import client as _client
|
||||
from core.http_errors import HTTPError, RequestException
|
||||
|
||||
# 异常层次与异步垫片(core.aiohttp_compat)共用同一份定义——调用方可用同一组
|
||||
# 类型捕获两条通道的失败。RequestException 在此再导出:music_downloader.models
|
||||
# 的 _RetryFromScratch 继承它,既有 except 与测试也直接导入它。
|
||||
# 异常层次见 core.http_errors(与调用方共用的 requests 同形定义)。RequestException
|
||||
# 在此再导出:music_downloader.models 的 _RetryFromScratch 继承它,既有 except
|
||||
# 与测试也直接导入它。
|
||||
__all__ = ['HTTPError', 'RequestException', 'Session', 'SyncResponse', 'get', 'post']
|
||||
|
||||
_DEFAULT_TIMEOUT = 30
|
||||
|
||||
Reference in new issue
Block a user