gather.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import flickrapi, json, os
  2. import settings_local as settings
  3. ROOT = os.path.dirname(os.path.realpath(__file__))
  4. # Instantiate flickr client
  5. flickr = flickrapi.FlickrAPI(settings.FLICKR_KEY, settings.FLICKR_SECRET)
  6. (token, frob) = flickr.get_token_part_one(perms='write')
  7. if not token: raw_input("Press ENTER after you authorized this program")
  8. flickr.get_token_part_two((token, frob))
  9. # Create data dir if don't exists
  10. d = os.path.join(ROOT, 'data')
  11. if not os.path.exists(d):
  12. os.makedirs(d)
  13. # Populate a list of dicts with photosets id and titles
  14. photosets = [
  15. {
  16. 'id': ps.attrib['id'],
  17. 'title': ps[0].text
  18. } for ps in flickr.photosets_getList()[0]
  19. ]
  20. for i in range(len(photosets)):
  21. photoset = photosets[i]
  22. f = os.path.join(d, '%s.json' % (photoset['id']))
  23. if not os.path.isfile(f):
  24. photos = flickr.photosets_getPhotos(photoset_id=photoset['id'])[0]
  25. photos = [
  26. {
  27. 'id': photo.attrib['id'],
  28. 'title': photo.attrib['title'],
  29. } for photo in photos
  30. ]
  31. for j in range(len(photos)):
  32. sizes = flickr.photos_getSizes(photo_id=photos[j]['id'])[0]
  33. photos[j]['sizes'] = {
  34. size.attrib['label'].lower(): {
  35. 'width': size.attrib['width'],
  36. 'height': size.attrib['height'],
  37. 'source': size.attrib['source'],
  38. } for size in sizes
  39. }
  40. photoset['photos'] = photos
  41. with open(f, 'w') as jsonfile:
  42. json.dump(photoset, jsonfile, indent=4)