使用 Python 代码将原始 JSON 数据上传到 Google 云存储
Upload raw JSON data on Google Cloud Storage using Python code
我正在尝试在 Google 云平台上上传原始 JSON 数据。但我收到此错误:
TypeError: must be string or buffer, not dict
代码:
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
代码通过将 StringIO(content)
更改为 StringIO(json.dumps(content))
在你的例子中,content
是一个字典。也许您想使用 json?
content = json.dumps({'name': 'test'})
回答我自己关于如何让它工作的评论问题:
要使其正常工作,您需要
from googleapiclient.discovery import build
from googleapiclient import http
from oauth2client.client import GoogleCredentials
import io
我还需要更改此设置:
media = http.MediaIoBaseUpload(StringIO(content), mimetype='plain/text')
在此:
media = http.MediaIoBaseUpload(io.StringIO(json.dumps(content)), mimetype='plain/text')
请注意 'io' 除了 Corey Goldberg 推荐的 json.dumps 之外的插入。
对于 predefinedAcl 选项你可以去这里:
https://cloud.google.com/storage/docs/access-control/lists#predefined-acl
Bucket 需要是您的存储桶的全名。如果您来自 firebase,则为“[name].appspot.com”
我正在尝试在 Google 云平台上上传原始 JSON 数据。但我收到此错误:
TypeError: must be string or buffer, not dict
代码:
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
代码通过将 StringIO(content)
更改为 StringIO(json.dumps(content))
在你的例子中,content
是一个字典。也许您想使用 json?
content = json.dumps({'name': 'test'})
回答我自己关于如何让它工作的评论问题:
要使其正常工作,您需要
from googleapiclient.discovery import build
from googleapiclient import http
from oauth2client.client import GoogleCredentials
import io
我还需要更改此设置:
media = http.MediaIoBaseUpload(StringIO(content), mimetype='plain/text')
在此:
media = http.MediaIoBaseUpload(io.StringIO(json.dumps(content)), mimetype='plain/text')
请注意 'io' 除了 Corey Goldberg 推荐的 json.dumps 之外的插入。
对于 predefinedAcl 选项你可以去这里:
https://cloud.google.com/storage/docs/access-control/lists#predefined-acl
Bucket 需要是您的存储桶的全名。如果您来自 firebase,则为“[name].appspot.com”