Skip to content

Commit

Permalink
🐛 Fix timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
Freed-Wu committed Dec 19, 2023
1 parent 5f1eaa9 commit b8cd24e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
26 changes: 17 additions & 9 deletions src/translate_shell/translators/online/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
"""
import logging
from dataclasses import dataclass
from typing import Any

from aiohttp import ClientSession
from aiohttp.client import ClientTimeout

from .. import Translator

Expand All @@ -16,14 +18,15 @@ class OnlineTranslator(Translator):
"""OnlineTranslator. All other online translators must be its subclass."""

name: str
timeout: int = 5

async def http_get(
self,
url: str,
session: ClientSession | None,
params: dict[str, str] | None = None,
headers: dict[str, str] | None = None,
cookies: dict[str, Any] | None = None,
timeout: int = 1,
) -> str:
"""Http get.
Expand All @@ -35,24 +38,29 @@ async def http_get(
:type params: dict[str, str] | None
:param headers:
:type headers: dict[str, str] | None
:param cookies:
:type cookies: dict[str, Any] | None
:param timeout:
:type timeout: int
:rtype: str
"""
if session is None:
_session = ClientSession()
else:
_session = session
session = ClientSession()
text = ""
try:
async with _session.get(
url, params=params, headers=headers
async with session.get(
url,
params=params,
headers=headers,
cookies=cookies,
timeout=ClientTimeout(timeout),
) as resp:
text = await resp.text()
except Exception:
except TimeoutError:
logger.warning(
"Translator %s timed out, please check your network", self.name
)
if session is None:
await _session.close()
await session.close()
return text

@staticmethod
Expand Down
1 change: 0 additions & 1 deletion src/translate_shell/translators/online/haici.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class HaiciTranslator(OnlineTranslator):
"""HaiciTranslator."""

name: str = "haici"
timeout: int = 15

async def __call__(
self, text: str, tl: str, sl: str, option: dict[str, Any]
Expand Down

0 comments on commit b8cd24e

Please sign in to comment.