flickr.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Flickr (Images)
  4. More info on api-key : https://www.flickr.com/services/apps/create/
  5. """
  6. from json import loads
  7. from urllib.parse import urlencode
  8. # about
  9. about = {
  10. "website": 'https://www.flickr.com',
  11. "wikidata_id": 'Q103204',
  12. "official_api_documentation": 'https://secure.flickr.com/services/api/flickr.photos.search.html',
  13. "use_official_api": True,
  14. "require_api_key": True,
  15. "results": 'JSON',
  16. }
  17. categories = ['images']
  18. nb_per_page = 15
  19. paging = True
  20. api_key = None
  21. url = (
  22. 'https://api.flickr.com/services/rest/?method=flickr.photos.search'
  23. + '&api_key={api_key}&{text}&sort=relevance'
  24. + '&extras=description%2C+owner_name%2C+url_o%2C+url_n%2C+url_z'
  25. + '&per_page={nb_per_page}&format=json&nojsoncallback=1&page={page}'
  26. )
  27. photo_url = 'https://www.flickr.com/photos/{userid}/{photoid}'
  28. paging = True
  29. def build_flickr_url(user_id, photo_id):
  30. return photo_url.format(userid=user_id, photoid=photo_id)
  31. def request(query, params):
  32. params['url'] = url.format(
  33. text=urlencode({'text': query}), api_key=api_key, nb_per_page=nb_per_page, page=params['pageno']
  34. )
  35. return params
  36. def response(resp):
  37. results = []
  38. search_results = loads(resp.text)
  39. # return empty array if there are no results
  40. if 'photos' not in search_results:
  41. return []
  42. if 'photo' not in search_results['photos']:
  43. return []
  44. photos = search_results['photos']['photo']
  45. # parse results
  46. for photo in photos:
  47. if 'url_o' in photo:
  48. img_src = photo['url_o']
  49. elif 'url_z' in photo:
  50. img_src = photo['url_z']
  51. else:
  52. continue
  53. # For a bigger thumbnail, keep only the url_z, not the url_n
  54. if 'url_n' in photo:
  55. thumbnail_src = photo['url_n']
  56. elif 'url_z' in photo:
  57. thumbnail_src = photo['url_z']
  58. else:
  59. thumbnail_src = img_src
  60. # append result
  61. results.append(
  62. {
  63. 'url': build_flickr_url(photo['owner'], photo['id']),
  64. 'title': photo['title'],
  65. 'img_src': img_src,
  66. 'thumbnail_src': thumbnail_src,
  67. 'content': photo['description']['_content'],
  68. 'author': photo['ownername'],
  69. 'template': 'images.html',
  70. }
  71. )
  72. # return results
  73. return results