upload.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import boto, json, os, urllib2, StringIO
  2. import settings_local as settings
  3. from boto.s3.key import Key
  4. from os import walk
  5. ROOT = os.path.dirname(os.path.realpath(__file__))
  6. # Instantiate aws client
  7. aws = boto.connect_s3(settings.AWS_KEY, settings.AWS_SECRET)
  8. bucket = aws.get_bucket(settings.AWS_BUCKET)
  9. bucket_keys = [k.key for k in bucket.list()]
  10. def set_key_from_string(key, data):
  11. print('Trying to set key string for %s' % key)
  12. if not key in bucket_keys:
  13. print('-- Setting %s' % key)
  14. k = Key(bucket)
  15. k.key = key
  16. k.set_contents_from_string(data)
  17. else:
  18. print('-- Already set')
  19. def set_key_from_url(key, url):
  20. print('Trying to set key string for %s' % key)
  21. if not key in bucket_keys:
  22. print('-- Setting %s' % key)
  23. k = Key(bucket)
  24. k.key = key
  25. file_object = urllib2.urlopen(url)
  26. fp = StringIO.StringIO(file_object.read())
  27. k.set_contents_from_file(fp)
  28. else:
  29. print('-- Already set')
  30. data_dir = 'data'
  31. for (dirpath, dirnames, filenames) in walk(os.path.join(ROOT, data_dir)):
  32. for f in filenames:
  33. json_file = open(os.path.join(ROOT, data_dir, f))
  34. data = json.load(json_file)
  35. set_key_from_string(
  36. '%s/info.json' % data['id'],
  37. json.dumps(
  38. {
  39. 'title': data['title']
  40. },
  41. indent=4
  42. )
  43. )
  44. # Tour photos
  45. for photo in data['photos']:
  46. set_key_from_string(
  47. '%s/%s.%s' % (data['id'], photo['id'], 'json'),
  48. json.dumps(
  49. {
  50. 'title': photo['title']
  51. },
  52. indent=4
  53. )
  54. )
  55. for k in photo['sizes'].keys():
  56. set_key_from_url(
  57. '%s/%s_%s.jpg' % (data['id'], photo['id'], k),
  58. photo['sizes'][k]['source']
  59. )