Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a JSON to google cloud storage via python

I am trying to upload a JSON I have to google cloud storage. I can do it manually so I know it works but now want to write a python script that will do it automatically.

import boto
import gcs_oauth2_boto_plugin
import os
import shutil
import StringIO
import tempfile
import time

from google.cloud import storage
from google.cloud.storage import blob

client = storage.Client(project='dataworks-356fa')
bucket = client.get_bucket('dataworks-356fa-backups')
blob = bucket.blob('t.json')
with open('t.json', 'rb') as f:
  blob.upload_from_file('f')

is the code I have so far and this is the error I am getting.

Traceback (most recent call last):
  File "uploadcloud.py", line 16, in <module>
    blob.upload_from_file('f')
  File "/Library/Python/2.7/site-packages/google/cloud/storage/blob.py", line 891, in upload_from_file
    client, file_obj, content_type, size, num_retries)
  File "/Library/Python/2.7/site-packages/google/cloud/storage/blob.py", line 815, in _do_upload
    client, stream, content_type, size, num_retries)
  File "/Library/Python/2.7/site-packages/google/cloud/storage/blob.py", line 634, in _do_multipart_upload
    data = stream.read()
AttributeError: 'str' object has no attribute 'read'
like image 703
W. Stephens Avatar asked Nov 08 '25 21:11

W. Stephens


1 Answers

You should pass an opened file to upload_from_file not string, just change to

with open('t.json', 'rb') as f:
  blob.upload_from_file(f)
like image 122
Logovsky Dmitry Avatar answered Nov 10 '25 12:11

Logovsky Dmitry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!