| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2016 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 from gcloud import storage |
| 6 from oauth2client.client import GoogleCredentials |
| 7 |
| 8 |
| 9 class GoogleStorageAccessor(object): |
| 10 """Utility class providing helpers for Google Cloud Storage. |
| 11 """ |
| 12 def __init__(self, project_name, bucket_name): |
| 13 """project_name is the name of the Google Cloud project. |
| 14 bucket_name is the name of the bucket that is used for Cloud Storage calls. |
| 15 """ |
| 16 self._credentials = GoogleCredentials.get_application_default() |
| 17 self._project_name = project_name |
| 18 self._bucket_name = bucket_name |
| 19 |
| 20 def _GetStorageClient(self): |
| 21 """Returns the storage client associated with the project""" |
| 22 return storage.Client(project = self._project_name, |
| 23 credentials = self._credentials) |
| 24 |
| 25 def _GetStorageBucket(self, storage_client): |
| 26 return storage_client.get_bucket(self._bucket_name) |
| 27 |
| 28 def UploadFile(self, filename_src, filename_dest): |
| 29 """Uploads a file to Google Cloud Storage |
| 30 |
| 31 Args: |
| 32 filename_src: name of the local file |
| 33 filename_dest: name of the file in Google Cloud Storage |
| 34 |
| 35 Returns: |
| 36 The URL of the file in Google Cloud Storage. |
| 37 """ |
| 38 client = self._GetStorageClient() |
| 39 bucket = self._GetStorageBucket(client) |
| 40 blob = bucket.blob(filename_dest) |
| 41 with open(filename_src) as file_src: |
| 42 blob.upload_from_file(file_src) |
| 43 return blob.public_url |
| 44 |
| 45 def UploadString(self, data_string, filename_dest): |
| 46 """Uploads a string to Google Cloud Storage |
| 47 |
| 48 Args: |
| 49 data_string: the contents of the file to be uploaded |
| 50 filename_dest: name of the file in Google Cloud Storage |
| 51 |
| 52 Returns: |
| 53 The URL of the file in Google Cloud Storage. |
| 54 """ |
| 55 client = self._GetStorageClient() |
| 56 bucket = self._GetStorageBucket(client) |
| 57 blob = bucket.blob(filename_dest) |
| 58 blob.upload_from_string(data_string) |
| 59 return blob.public_url |
| 60 |
| OLD | NEW |