Naveen
Naveen

Reputation: 677

Upload raw JSON data on Google Cloud Storage using Python code

I am trying to upload raw JSON data on Google Cloud Platform. But I am getting this error:

TypeError: must be string or buffer, not dict

Code:

def upload_data(destination_path):
    credentials = GoogleCredentials.get_application_default()
    service = discovery.build('storage', 'v1', credentials=credentials)

    content = {'name': 'test'}
    media = http.MediaIoBaseUpload(StringIO(content), mimetype='plain/text')
    req = service.objects().insert(
        bucket=settings.GOOGLE_CLOUD_STORAGE_BUCKET,
        body={"cacheControl": "public,max-age=31536000"},
        media_body=media,
        predefinedAcl='publicRead',
        name=destination_path,
    )
    resp = req.execute()

    return resp

Code Worked by changing StringIO(content) to StringIO(json.dumps(content))

Upvotes: 1

Views: 2610

Answers (2)

Michel K
Michel K

Reputation: 701

To answer my own comment question on how to get this to work:

To get this to work you'll need

from googleapiclient.discovery import build
from googleapiclient import http
from oauth2client.client import GoogleCredentials
import io

Also i needed to change this:

 media = http.MediaIoBaseUpload(StringIO(content), mimetype='plain/text')

in to this:

media = http.MediaIoBaseUpload(io.StringIO(json.dumps(content)), mimetype='plain/text')

Note the insert of 'io' besides the json.dumps recommended by Corey Goldberg.

for predefinedAcl options you can go here:

https://cloud.google.com/storage/docs/access-control/lists#predefined-acl

Bucket needs to be the full name of your bucket. If you come from firebase it's "[name].appspot.com"

Upvotes: 0

Corey Goldberg
Corey Goldberg

Reputation: 60604

in your example, content is a dict. Perhaps you want to use json?

content = json.dumps({'name': 'test'})

Upvotes: 3

Related Questions