1 # Copyright 2013 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 5 """Implementation of CloudBucket using Google Cloud Storage as the backend.""" 6 import os 7 import sys 8 9 import cloudstorage 10 11 from ..common import cloud_bucket 12 13 14 class GoogleCloudStorageBucket(cloud_bucket.BaseCloudBucket): 15 """Subclass of cloud_bucket.CloudBucket with actual GS commands.""" 16 17 def __init__(self, bucket): 18 """Initializes the bucket. 19 20 Args: 21 bucket: the name of the bucket to connect to. 22 """ 23 self.bucket = '/' + bucket 24 25 def _full_path(self, path): 26 return self.bucket + '/' + path.lstrip('/') 27 28 # override 29 def UploadFile(self, path, contents, content_type): 30 gs_file = cloudstorage.open( 31 self._full_path(path), 'w', content_type=content_type) 32 gs_file.write(contents) 33 gs_file.close() 34 35 # override 36 def DownloadFile(self, path): 37 try: 38 gs_file = cloudstorage.open(self._full_path(path), 'r') 39 r = gs_file.read() 40 gs_file.close() 41 except Exception as e: 42 raise Exception('%s: %s' % (self._full_path(path), str(e))) 43 return r 44 45 # override 46 def UpdateFile(self, path, contents): 47 if not self.FileExists(path): 48 raise cloud_bucket.FileNotFoundError 49 gs_file = cloudstorage.open(self._full_path(path), 'w') 50 gs_file.write(contents) 51 gs_file.close() 52 53 # override 54 def RemoveFile(self, path): 55 cloudstorage.delete(self._full_path(path)) 56 57 # override 58 def FileExists(self, path): 59 try: 60 cloudstorage.stat(self._full_path(path)) 61 except cloudstorage.NotFoundError: 62 return False 63 return True 64 65 # override 66 def GetImageURL(self, path): 67 return '/image?file_path=%s' % path 68 69 # override 70 def GetAllPaths(self, prefix): 71 return (f.filename[len(self.bucket) + 1:] for f in 72 cloudstorage.listbucket(self.bucket, prefix=prefix)) 73