Coverage for app/venv/lib/python3.14/site-packages/weblate/utils/requests.py: 83%

39 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 07:15 +0000

1# Copyright © Michal Čihař <michal@weblate.org> 

2# 

3# SPDX-License-Identifier: GPL-3.0-or-later 

4 

5from __future__ import annotations 

6 

7from typing import TYPE_CHECKING 

8 

9import requests 

10from django.core.cache import cache 

11 

12from weblate.logger import LOGGER 

13from weblate.utils.version import USER_AGENT 

14 

15if TYPE_CHECKING: 15 ↛ 16line 15 didn't jump to line 16 because the condition on line 15 was never true

16 from requests import Response 

17 

18 

19def request( 

20 method: str, 

21 url: str, 

22 *, 

23 headers: dict[str, str] | None = None, 

24 timeout: float = 5, 

25 raise_for_status: bool = True, 

26 **kwargs, 

27) -> Response: 

28 agent = {"User-Agent": USER_AGENT} 

29 if headers is None: 29 ↛ 32line 29 didn't jump to line 32 because the condition on line 29 was always true

30 headers = agent 

31 else: 

32 headers.update(agent) 

33 response = requests.request(method, url, headers=headers, timeout=timeout, **kwargs) 

34 if raise_for_status: 34 ↛ 36line 34 didn't jump to line 36 because the condition on line 34 was always true

35 response.raise_for_status() 

36 return response 

37 

38 

39def get_uri_error(uri: str) -> str | None: 

40 """Return error for fetching the URL or None if it works.""" 

41 if uri.startswith("https://nonexisting.weblate.org/"): 41 ↛ 42line 41 didn't jump to line 42 because the condition on line 41 was never true

42 return "Non existing test URL" 

43 cache_key = f"uri-check-{uri}" 

44 cached = cache.get(cache_key) 

45 if cached is True: 

46 LOGGER.debug("URL check for %s, cached success", uri) 

47 return None 

48 if cached: 

49 # The cache contains string here 

50 LOGGER.debug("URL check for %s, cached failure", uri) 

51 return cached 

52 try: 

53 with request("get", uri, stream=True): 

54 cache.set(cache_key, True, 12 * 3600) 

55 LOGGER.debug("URL check for %s, tested success", uri) 

56 return None 

57 except requests.exceptions.RequestException as error: 

58 if getattr(error.response, "status_code", 0) == 429: 58 ↛ 60line 58 didn't jump to line 60 because the condition on line 58 was never true

59 # Silently ignore rate limiting issues 

60 return None 

61 result = str(error) 

62 cache.set(cache_key, result, 3600) 

63 return result