unsplash_service.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """Unsplash图片服务"""
  2. import requests
  3. from typing import List, Optional
  4. from ..config import get_settings
  5. class UnsplashService:
  6. """Unsplash图片服务类"""
  7. def __init__(self):
  8. """初始化服务"""
  9. settings = get_settings()
  10. self.access_key = settings.unsplash_access_key
  11. self.base_url = "https://api.unsplash.com"
  12. def search_photos(self, query: str, per_page: int = 5) -> List[dict]:
  13. """
  14. 搜索图片
  15. Args:
  16. query: 搜索关键词
  17. per_page: 每页数量
  18. Returns:
  19. 图片列表
  20. """
  21. try:
  22. url = f"{self.base_url}/search/photos"
  23. params = {
  24. "query": query,
  25. "per_page": per_page,
  26. "client_id": self.access_key
  27. }
  28. response = requests.get(url, params=params, timeout=10)
  29. response.raise_for_status()
  30. data = response.json()
  31. results = data.get("results", [])
  32. # 提取图片URL
  33. photos = []
  34. for photo in results:
  35. photos.append({
  36. "id": photo.get("id"),
  37. "url": photo.get("urls", {}).get("regular"),
  38. "thumb": photo.get("urls", {}).get("thumb"),
  39. "description": photo.get("description") or photo.get("alt_description"),
  40. "photographer": photo.get("user", {}).get("name")
  41. })
  42. return photos
  43. except Exception as e:
  44. print(f"❌ Unsplash搜索失败: {str(e)}")
  45. return []
  46. def get_photo_url(self, query: str) -> Optional[str]:
  47. """
  48. 获取单张图片URL
  49. Args:
  50. query: 搜索关键词
  51. Returns:
  52. 图片URL
  53. """
  54. photos = self.search_photos(query, per_page=1)
  55. if photos:
  56. return photos[0].get("url")
  57. return None
  58. # 全局服务实例
  59. _unsplash_service = None
  60. def get_unsplash_service() -> UnsplashService:
  61. """获取Unsplash服务实例(单例模式)"""
  62. global _unsplash_service
  63. if _unsplash_service is None:
  64. _unsplash_service = UnsplashService()
  65. return _unsplash_service