2022-02-15 00:18:46 +08:00
|
|
|
|
# -*- coding: utf-8 -*-
|
2024-01-30 23:58:27 +08:00
|
|
|
|
import asyncio
|
2023-07-29 01:22:21 +08:00
|
|
|
|
from typing import *
|
|
|
|
|
|
2022-02-15 00:18:46 +08:00
|
|
|
|
import aiohttp
|
|
|
|
|
|
2022-09-28 00:11:29 +08:00
|
|
|
|
# 不带这堆头部有时候也能成功请求,但是带上后成功的概率更高
|
|
|
|
|
BILIBILI_COMMON_HEADERS = {
|
|
|
|
|
'Origin': 'https://www.bilibili.com',
|
|
|
|
|
'Referer': 'https://www.bilibili.com/',
|
|
|
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
|
2023-07-06 23:25:07 +08:00
|
|
|
|
' Chrome/114.0.0.0 Safari/537.36'
|
2022-10-09 18:53:42 +08:00
|
|
|
|
}
|
2022-09-28 00:11:29 +08:00
|
|
|
|
|
2023-07-29 01:22:21 +08:00
|
|
|
|
http_session: Optional[aiohttp.ClientSession] = None
|
|
|
|
|
|
|
|
|
|
|
2023-07-29 12:48:57 +08:00
|
|
|
|
def init():
|
2023-09-06 21:34:04 +08:00
|
|
|
|
global http_session
|
2024-01-30 23:58:27 +08:00
|
|
|
|
http_session = aiohttp.ClientSession(
|
|
|
|
|
response_class=CustomClientResponse,
|
|
|
|
|
timeout=aiohttp.ClientTimeout(total=10),
|
|
|
|
|
)
|
2023-07-29 12:48:57 +08:00
|
|
|
|
|
2023-09-06 21:34:04 +08:00
|
|
|
|
|
|
|
|
|
async def shut_down():
|
|
|
|
|
if http_session is not None:
|
|
|
|
|
await http_session.close()
|
2024-01-30 23:58:27 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CustomClientResponse(aiohttp.ClientResponse):
|
|
|
|
|
# 因为aiohttp的BUG,当底层连接断开时,_wait_released可能会抛出CancelledError,导致上层协程结束。这里改个错误类型
|
|
|
|
|
async def _wait_released(self):
|
|
|
|
|
try:
|
|
|
|
|
return await super()._wait_released()
|
|
|
|
|
except asyncio.CancelledError as e:
|
|
|
|
|
raise aiohttp.ClientConnectionError('Connection released') from e
|