models.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from __future__ import print_function
  2. from flask import url_for
  3. from url_for_s3 import url_for_s3
  4. from project import db
  5. class Thingy(db.Model):
  6. """Sample model for flask-s3-save-example."""
  7. id = db.Column(db.Integer(), primary_key=True)
  8. image = db.Column(db.String(255), default='')
  9. image_storage_type = db.Column(db.String(255), default='')
  10. image_storage_bucket_name = db.Column(db.String(255), default='')
  11. def __repr__(self):
  12. return 'A thingy'
  13. @property
  14. def image_url(self):
  15. from flask import current_app as app
  16. return (self.image
  17. and '%s%s' % (
  18. app.config['UPLOADS_RELATIVE_PATH'],
  19. self.image)
  20. or None)
  21. @property
  22. def image_url_storageaware(self):
  23. if not self.image:
  24. return None
  25. if not (
  26. self.image_storage_type
  27. and self.image_storage_bucket_name):
  28. return url_for(
  29. 'static',
  30. filename=self.image_url,
  31. _external=True)
  32. if self.image_storage_type != 's3':
  33. raise ValueError((
  34. 'Storage type "%s" is invalid, the only supported ' +
  35. 'storage type (apart from default local storage) ' +
  36. 'is s3.') % self.image_storage_type)
  37. return url_for_s3(
  38. 'static',
  39. bucket_name=self.image_storage_bucket_name,
  40. filename=self.image_url)