buildin_retrieval.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import json
  2. from os import path
  3. from pathlib import Path
  4. from typing import Optional
  5. from flask import current_app
  6. from services.recommend_app.recommend_app_base import RecommendAppRetrievalBase
  7. from services.recommend_app.recommend_app_type import RecommendAppType
  8. class BuildInRecommendAppRetrieval(RecommendAppRetrievalBase):
  9. """
  10. Retrieval recommended app from buildin, the location is constants/recommended_apps.json
  11. """
  12. builtin_data: Optional[dict] = None
  13. def get_type(self) -> str:
  14. return RecommendAppType.BUILDIN
  15. def get_recommended_apps_and_categories(self, language: str) -> dict:
  16. result = self.fetch_recommended_apps_from_builtin(language)
  17. return result
  18. def get_recommend_app_detail(self, app_id: str):
  19. result = self.fetch_recommended_app_detail_from_builtin(app_id)
  20. return result
  21. @classmethod
  22. def _get_builtin_data(cls) -> dict:
  23. """
  24. Get builtin data.
  25. :return:
  26. """
  27. if cls.builtin_data:
  28. return cls.builtin_data
  29. root_path = current_app.root_path
  30. cls.builtin_data = json.loads(
  31. Path(path.join(root_path, "constants", "recommended_apps.json")).read_text(encoding="utf-8")
  32. )
  33. return cls.builtin_data or {}
  34. @classmethod
  35. def fetch_recommended_apps_from_builtin(cls, language: str) -> dict:
  36. """
  37. Fetch recommended apps from builtin.
  38. :param language: language
  39. :return:
  40. """
  41. builtin_data: dict[str, dict[str, dict]] = cls._get_builtin_data()
  42. return builtin_data.get("recommended_apps", {}).get(language, {})
  43. @classmethod
  44. def fetch_recommended_app_detail_from_builtin(cls, app_id: str) -> Optional[dict]:
  45. """
  46. Fetch recommended app detail from builtin.
  47. :param app_id: App ID
  48. :return:
  49. """
  50. builtin_data: dict[str, dict[str, dict]] = cls._get_builtin_data()
  51. return builtin_data.get("app_details", {}).get(app_id)