flickr.py 2.6KB

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