flickr.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 = 'https://api.flickr.com/services/rest/?method=flickr.photos.search' +\
  22. '&api_key={api_key}&{text}&sort=relevance' +\
  23. '&extras=description%2C+owner_name%2C+url_o%2C+url_n%2C+url_z' +\
  24. '&per_page={nb_per_page}&format=json&nojsoncallback=1&page={page}'
  25. photo_url = 'https://www.flickr.com/photos/{userid}/{photoid}'
  26. paging = True
  27. def build_flickr_url(user_id, photo_id):
  28. return photo_url.format(userid=user_id, photoid=photo_id)
  29. def request(query, params):
  30. params['url'] = url.format(text=urlencode({'text': query}),
  31. api_key=api_key,
  32. nb_per_page=nb_per_page,
  33. page=params['pageno'])
  34. return params
  35. def response(resp):
  36. results = []
  37. search_results = loads(resp.text)
  38. # return empty array if there are no results
  39. if 'photos' not in search_results:
  40. return []
  41. if 'photo' not in search_results['photos']:
  42. return []
  43. photos = search_results['photos']['photo']
  44. # parse results
  45. for photo in photos:
  46. if 'url_o' in photo:
  47. img_src = photo['url_o']
  48. elif 'url_z' in photo:
  49. img_src = photo['url_z']
  50. else:
  51. continue
  52. # For a bigger thumbnail, keep only the url_z, not the url_n
  53. if 'url_n' in photo:
  54. thumbnail_src = photo['url_n']
  55. elif 'url_z' in photo:
  56. thumbnail_src = photo['url_z']
  57. else:
  58. thumbnail_src = img_src
  59. url = build_flickr_url(photo['owner'], photo['id'])
  60. # append result
  61. results.append({'url': url,
  62. 'title': photo['title'],
  63. 'img_src': img_src,
  64. 'thumbnail_src': thumbnail_src,
  65. 'content': photo['description']['_content'],
  66. 'author': photo['ownername'],
  67. 'template': 'images.html'})
  68. # return results
  69. return results