Coverage for otaku_info/external/myanimelist.py: 65%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

29 statements  

1"""LICENSE 

2Copyright 2020 Hermann Krumrey <hermann@krumreyh.com> 

3 

4This file is part of otaku-info. 

5 

6otaku-info is free software: you can redistribute it and/or modify 

7it under the terms of the GNU General Public License as published by 

8the Free Software Foundation, either version 3 of the License, or 

9(at your option) any later version. 

10 

11otaku-info is distributed in the hope that it will be useful, 

12but WITHOUT ANY WARRANTY; without even the implied warranty of 

13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14GNU General Public License for more details. 

15 

16You should have received a copy of the GNU General Public License 

17along with otaku-info. If not, see <http://www.gnu.org/licenses/>. 

18LICENSE""" 

19 

20import time 

21import json 

22import requests 

23from requests import ConnectionError 

24from requests.exceptions import ChunkedEncodingError 

25from typing import Optional 

26from jerrycan.base import app 

27from otaku_info.enums import MediaType 

28from otaku_info.external.entities.MyanimelistItem import MyanimelistItem 

29 

30 

31def load_myanimelist_item(myanimelist_id: int, media_type: MediaType) \ 

32 -> Optional[MyanimelistItem]: 

33 """ 

34 Loads myanimelist data using the jikan API 

35 :param myanimelist_id: The myanimelist ID 

36 :param media_type: The media type 

37 :return: The myanimelist item 

38 """ 

39 url = f"https://api.jikan.moe/v3/{media_type.value}/{myanimelist_id}" 

40 

41 try: 

42 response = requests.get(url) 

43 except (ChunkedEncodingError, ConnectionError): 

44 return None 

45 

46 if response.status_code == 503: 46 ↛ 48line 46 didn't jump to line 48, because the condition on line 46 was never true

47 # Sometimes jikan temporarily loses connection to myanimelist 

48 time.sleep(2) 

49 response = requests.get(url) 

50 elif response.status_code >= 300: 50 ↛ 51line 50 didn't jump to line 51, because the condition on line 50 was never true

51 return None 

52 

53 data = json.loads(response.text) 

54 if data["type"] == "BadResponseException": 54 ↛ 55line 54 didn't jump to line 55, because the condition on line 54 was never true

55 return None 

56 elif data["type"] == "RateLimitException": 56 ↛ 57line 56 didn't jump to line 57, because the condition on line 56 was never true

57 app.logger.warning("Rate limited by jikan") 

58 time.sleep(30) 

59 return load_myanimelist_item(myanimelist_id, media_type) 

60 

61 mal_item = MyanimelistItem.from_query(media_type, data) 

62 return mal_item