Skip to content

Commit

Permalink
feat(HTTPClient): 设置默认响应头
Browse files Browse the repository at this point in the history
  • Loading branch information
Akimio521 committed Nov 17, 2024
1 parent 5b12a68 commit 1015fc3
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions app/utils/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from httpx import AsyncClient, Client, Response, TimeoutException
from aiofile import async_open

from app.core import logger
from app.core import settings, logger
from app.utils.url import URLUtils
from app.utils.retry import Retry

Expand All @@ -20,9 +20,16 @@
class HTTPClient:
"""
HTTP 客户端类
"""

__mini_stream_size: int = 128 * 1024 * 1024 # 最小流式下载文件大小,128MB
# 最小流式下载文件大小,128MB
MINI_STREAM_SIZE: int = 128 * 1024 * 1024
# 默认请求头
HEADERS: dict[str, str] = {
"User-Agent": f"AutoFilm/{settings.APP_VERSION}",
"Accept": "application/json",
}

def __init__(self):
"""
Expand Down Expand Up @@ -128,6 +135,8 @@ def request(
:param kwargs: 其他请求参数,如 headers, cookies 等
:return: HTTP 响应对象
"""
headers = kwargs.get("headers", self.HEADERS)
kwargs["headers"] = headers
if sync:
return self._sync_request(method, url, **kwargs)
else:
Expand Down Expand Up @@ -311,7 +320,7 @@ async def __download_chunk(
headers["Range"] = f"bytes={start}-{end}"
kwargs["headers"] = headers

resp = await self.get(url, **kwargs)
resp = await self.get(url, sync=False, **kwargs)
async with async_open(file_path, "ab") as file:
file.seek(start)
async for chunk in resp.aiter_bytes(iter_chunked_size):
Expand All @@ -329,7 +338,7 @@ def caculate_divisional_range(
:param chunk_num: 分片数
:return: 分片范围
"""
if file_size < HTTPClient.__mini_stream_size or chunk_num <= 1:
if file_size < HTTPClient.MINI_STREAM_SIZE or chunk_num <= 1:
return [(0, file_size - 1)]

step = file_size // chunk_num # 计算每个分片的基本大小
Expand Down

0 comments on commit 1015fc3

Please sign in to comment.