fix: 异步学习请求不再把同步钩子当成协程

This commit is contained in:
2026-11-17 11:34:31 +08:00
parent 42964432a5
commit 11a3c5611a
3 changed files with 41 additions and 3 deletions
+3 -3
View File
@@ -35,7 +35,7 @@ from euniv.client import (
set_cookie,
as_uuid,
compact_id,
guard_https,
guard_https_async,
play_page_params,
study_progress_fields,
)
@@ -764,7 +764,7 @@ class StudySession:
timeout=30,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
event_hooks={"request": [guard_https]},
event_hooks={"request": [guard_https_async]},
)
_load_cookies(self._client, self._initial_cookies)
self._proxy_lock = asyncio.Lock()
@@ -804,7 +804,7 @@ class StudySession:
timeout=30,
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
event_hooks={"request": [guard_https]},
event_hooks={"request": [guard_https_async]},
)
cookies = self._initial_cookies
if self._client is not None:
+5
View File
@@ -808,6 +808,11 @@ def guard_https(request: httpx.Request) -> None:
request.headers.pop("Token", None)
async def guard_https_async(request: httpx.Request) -> None:
"""httpx 异步客户端会 await 钩子的返回值,同步函数会得到 None。"""
guard_https(request)
def _login_secret_too_long(value: str) -> bool:
return len(value.encode("utf-8")) > 245
+33
View File
@@ -153,6 +153,39 @@ def test_qr_login_stores_scan_mark(monkeypatch) -> None:
assert "secret" not in decrypt_secret(account.password_cipher)
def test_async_study_hook_can_be_awaited() -> None:
import asyncio
import inspect
import httpx
from euniv.autostudy import StudySession
seen: dict[str, str | None] = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["host"] = request.url.host
seen["token"] = request.headers.get("token")
return httpx.Response(200, text="ok")
async def main() -> None:
async with StudySession("secret-token", []) as session:
hook = session._client._event_hooks["request"][0]
assert inspect.iscoroutinefunction(hook)
async with httpx.AsyncClient(
transport=httpx.MockTransport(handler),
event_hooks={"request": [hook]},
) as client:
other = await client.get("https://example.com/x", headers={"token": "secret-token"})
assert other.status_code == 200
assert seen["token"] is None
kept = await client.get("https://euniv.zte.com.cn/kng/view/video/x.html", headers={"token": "secret-token"})
assert kept.status_code == 200
assert seen["token"] == "secret-token"
asyncio.run(main())
def test_secure_cookie_is_written_through_the_jar() -> None:
client = EunivClient("6650000146", "secret-pass")
try: