2

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!

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

5 Comments

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!
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.
I think this is the example you are looking for stackoverflow.com/questions/37003862/…. Let me know if this works for you!
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
The last link works for me. Thank you.. I did step by step, and made it on Python eventually. Thank you so muuuuch
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.