How to upload a file to Google Cloud Storage on Python 3?

前端 未结 4 1073
刺人心
刺人心 2020-12-02 14:41

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

4条回答
  •  温柔的废话
    2020-12-02 14:44

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

提交回复
热议问题