简体   繁体   中英

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))

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

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM