如何在Python 3上将文件上传到Google Cloud Storage? [英] How to upload a file to Google Cloud Storage on Python 3?
问题描述
如何从Python 3将文件上传到 Google云存储?最终是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屋!