如何在 Python 3 上将文件上传到 Google Cloud Storage? [英] How to upload a file to Google Cloud Storage on Python 3?

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

问题描述

如何将文件从 Python 3 上传到 Google Cloud Storage?最终是 Python 2,如果它在 Python 3 中不可行的话.

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

我看了又看,但还没有找到真正有效的解决方案.我尝试了 boto,但是当我尝试通过 gsutil config -e 生成必要的 .boto 文件时,它一直说我需要通过 gcloud auth login 配置身份验证.然而,我已经做了很多次后者,但没有帮助.

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.

推荐答案

使用标准的gcloud 库,同时支持 Python 2 和 Python 3.

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

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

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

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