storage.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from datetime import datetime,timedelta
  2. from adm.constants import CTS as cts
  3. from django.core.files.uploadedfile import InMemoryUploadedFile
  4. from django.core.files.base import ContentFile
  5. from storages.backends.gcloud import GoogleCloudStorage
  6. from google.oauth2 import service_account
  7. import os
  8. import json
  9. class MediaStorage():
  10. def __init__(self, container=None):
  11. self.storage = None
  12. self.container = container
  13. if cts.STORAGE_TYPE == "GCP":
  14. if self.container is None:
  15. self.container = cts.GCP_ST_INFODRIVERS
  16. self.storage = GoogleCloudStorage()
  17. baseDir = os.path.dirname(os.path.realpath(__file__))
  18. if cts.AMBIENTE_EC2=="PROD":
  19. pathCredentials = baseDir + "/auth/credentials_gcp_storage.json"
  20. else:
  21. pathCredentials = baseDir + "/auth/credentials_gcp_stg_storage.json"
  22. with open(pathCredentials) as credentials:
  23. self.credentials = json.load(credentials)
  24. self.storage.credentials = service_account.Credentials.from_service_account_file(pathCredentials)
  25. self.storage.project_id = cts.GCP_ST_ACCESS_ID
  26. self.storage.bucket_name = cts.GCP_ST_ACCESS_KEY_ID
  27. self.location = self.container + "\\"
  28. def exists(self, path_midia_bucket):
  29. return self.storage.exists(path_midia_bucket)
  30. def delete(self, path_midia_bucket):
  31. self.storage.delete(path_midia_bucket)
  32. def url(self, path_midia_bucket,expire=None):
  33. ret = ""
  34. if expire is None:
  35. expire = 600
  36. elif expire==-1:
  37. expire = None
  38. if cts.STORAGE_TYPE == "GCP":
  39. if expire is None:
  40. self.storage.expiration = None
  41. else:
  42. self.storage.expiration = datetime.utcnow() + timedelta(seconds=expire)
  43. ret = self.storage.url(path_midia_bucket)
  44. else:
  45. ret = self.storage.url(path_midia_bucket,expire)
  46. return ret
  47. def save(self, path_midia_bucket, content,max_length=None):
  48. if cts.STORAGE_TYPE == "GCP":
  49. if isinstance(content,InMemoryUploadedFile):
  50. path_midia_bucket = path_midia_bucket.replace("/","\\")
  51. arrTMP = path_midia_bucket.split("\\")
  52. path_midia_bucket = path_midia_bucket.replace(arrTMP[0]+"\\",cts.GCP_ST_GENERAL + "\\")
  53. if self.exists(path_midia_bucket):
  54. self.delete(path_midia_bucket)
  55. self.storage.save(path_midia_bucket, content.file)
  56. else:
  57. try:
  58. self.storage.save(path_midia_bucket, content)
  59. except:
  60. self.storage.save(path_midia_bucket, ContentFile(content))
  61. def generate_filename(self,filename):
  62. return filename
  63. def list(self, prefix=None):
  64. # Get blobs in specific subirectory
  65. blobs = list(self.storage.bucket.list_blobs(prefix=prefix))
  66. return blobs