Google云端存储 - 如何从Python 3上传文件? [英] Google Cloud Storage - How to upload a file from Python 3?

查看:1001
本文介绍了Google云端存储 - 如何从Python 3上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将文件上传到Python 3的 Google云端存储?最终Python 2,如果它不适用于Python 3。



我已经看过并期待,但还没有找到实际可行的解决方案。我尝试了 boto ,但是当我尝试通过 gsutil生成必要的.boto文件时config -e ,它一直说我需要通过 gcloud auth login 来配置身份验证。然而,我已经做了很多次,没有它的帮助。 使用标准的 gcloud 库,它同时支持Python 2和Python 3.

将文件上传到云存储的示例



  from gcloud import storage $ b $ from oauth2client.service_account import ServiceAccountCredentials 
import


credentials_dict = {
'type':'service_account',$ b $'client_id':os.environ ['BACKUP_CLIENT_ID'],
'client_email':os.environ ['BACKUP_CLIENT_EMAIL'],
'private_key_id':os.environ ['BACKUP_PRIVATE_KEY_ID'],
'private_key':os.environ ['BACKUP_PRIVATE_KEY'],
}
凭证= ServiceAccountCredentials.from_json_keyfile_dict(
credentials_dict

client = storage.Client(凭证=凭证, project ='myproject')
bucket = client.get_bucket('mybucket')
blob = bucket.blob('myfile')
blob.upload_from_filename('myfile')


How can I upload a file to Google Cloud Storage from Python 3? Eventually Python 2, if it's infeasible from Python 3.

I've looked and looked, but haven't found a solution that actually works. I tried boto, but when I try to generate the necessary .boto file through gsutil config -e, it keeps saying that I need to configure authentication through gcloud auth login. However, I have done the latter a number of times, without it helping.

解决方案

Use the standard gcloud library, which supports both Python 2 and Python 3.

Example of Uploading File to Cloud Storage

from gcloud import storage
from oauth2client.service_account import ServiceAccountCredentials
import os


credentials_dict = {
    'type': 'service_account',
    'client_id': os.environ['BACKUP_CLIENT_ID'],
    'client_email': os.environ['BACKUP_CLIENT_EMAIL'],
    'private_key_id': os.environ['BACKUP_PRIVATE_KEY_ID'],
    'private_key': os.environ['BACKUP_PRIVATE_KEY'],
}
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    credentials_dict
)
client = storage.Client(credentials=credentials, project='myproject')
bucket = client.get_bucket('mybucket')
blob = bucket.blob('myfile')
blob.upload_from_filename('myfile')

这篇关于Google云端存储 - 如何从Python 3上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆