How to upload a bytes image on Google Cloud Storage from a Python script

前端 未结 3 1427
清酒与你
清酒与你 2020-12-16 03:52

I want to upload an image on Google Cloud Storage from a python script. This is my code:

from oauth2client.service_account import ServiceAccountCredentials
f         


        
3条回答
  •  死守一世寂寞
    2020-12-16 04:34

    MediaIoBaseUpload expects an io.Base-like object and raises following error:

      'numpy.ndarray' object has no attribute 'seek'
    

    upon receiving a ndarray object. To solve it I am using TemporaryFile and numpy.ndarray().tofile()

    from oauth2client.service_account import ServiceAccountCredentials
    from googleapiclient import discovery
    import googleapiclient
    import numpy as np
    import cv2
    from tempfile import TemporaryFile
    
    
    scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scopes)
    service = discovery.build('storage','v1',credentials = credentials)
    
    body = {'name':'my_image.jpg'}
    with TemporaryFile() as gcs_image:
        cv2.imread('img.jpg').tofile(gcs_image)
        req = service.objects().insert(
           bucket='my_bucket’, body=body,
           media_body=googleapiclient.http.MediaIoBaseUpload(
              gcs_image, 'application/octet-stream'))
    
        resp = req.execute()
    

    Be aware that googleapiclient is non-idiomatic and maintenance only(it’s not developed anymore). I would recommend using idiomatic one.

提交回复
热议问题