1

I'm literally stuck on some function. I want to write the code to upload file to Google Cloud Storage using Python, but I don't know where should I start.

I'd looked into docs from everywhere, but it shows only at Google Cloud Shell.

If anyone knows about this, enlighten me please!

Have a good one!

Rafa Guillermo
  • 14,474
  • 3
  • 18
  • 54
fernando
  • 13
  • 1
  • 3

2 Answers2

4

You can do it in this way,

from gcloud import storage

client = storage.Client()

bucket = client.get_bucket('<your-bucket-name>')

blob = bucket.blob('my-test-file.txt')

filename = "%s/%s" % (folder, filename)
blob = bucket.blob(filename)

# Uploading string of text
blob.upload_from_string('this is test content!')

# Uploading from a local file using open()
with open('photo.jpg', 'rb') as photo:
    blob.upload_from_file(photo)

# Uploading from local file without open()
blob.upload_from_filename('photo.jpg')

blob.make_public()
url = blob.public_url

For an explanation of each of the above line check out this blog post (example for the above is taken from this blog): https://riptutorial.com/google-cloud-storage/example/28256/upload-files-using-python

Let's_Create
  • 2,963
  • 3
  • 14
  • 33
  • Hey,, thank you for the comment. I've looked into it earlier. My curious is where should I put public storage URL in there? and what about authentication part?? If you had some test before I would you like to get some examples for me. Thx! – fernando Jun 01 '20 at 04:27
  • For the authentication part you can add as parameter to the client method. I have done it with AWS but this seems almost similar. If i get any examples will share it here. – Let's_Create Jun 01 '20 at 04:35
  • I think this is the example you are looking for https://stackoverflow.com/questions/37003862/google-cloud-storage-how-to-upload-a-file-from-python-3. Let me know if this works for you! – Let's_Create Jun 01 '20 at 04:42
  • 1
    On cloud shell, it works like a charm. But I was curious about when I run python on my local system to upload files to GCS. Thx though. It's probably lack of understanding about programming. I appreciate of your help – fernando Jun 01 '20 at 05:49
  • 1
    The last link works for me. Thank you.. I did step by step, and made it on Python eventually. Thank you so muuuuch – fernando Jun 01 '20 at 06:30
1

Here's a very easy method

from google.cloud import storage
           
def upload_blob(bucket_name, source_file_name, destination_blob_name):
  """Uploads a file to the bucket."""

  storage_client = storage.Client()

  bucket = storage_client.get_bucket(bucket_name)
  blob = bucket.blob(destination_blob_name)
  blob.upload_from_file(source_file_name)



upload_blob('bucketName', 'myText2.txt', "myText")

Just replace arguments of the function to match your file and bucket.

Franco
  • 441
  • 3
  • 18