【问题标题】:How to read data in cloud storage data using clouds functions如何使用云函数读取云存储数据中的数据
【发布时间】:2020-08-07 12:16:54
【问题描述】:

我正在尝试使用 python 创建一个云函数,它从云存储中的目录中读取包含表模式的 json 文件,并且我需要从这些模式中在 bigquery 中创建表。

我曾尝试访问云存储,但没有成功,之前我在 google colab 中开发了类似的东西,从驱动器上的目录中读取这些模式,但现在情况似乎完全不同了。

有人可以帮我吗?

【问题讨论】:

    标签: python google-cloud-functions google-cloud-storage


    【解决方案1】:

    您可以查看GCP的Streaming data from Cloud Storage into BigQuery using Cloud Functions解决方案指南。

    如果您想要不同的方法,可以参考GCP doc 的下载对象指南从 GCS 检索数据,请参阅下面的示例代码。

    from google.cloud import storage
    
    
    def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"
    
    storage_client = storage.Client()
    
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)
    
    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )
    

    【讨论】:

    • 那会是什么? # source_blob_name = "存储对象名称"
    • 当您在 GCS 存储桶中有文件时,包括任何目录的文件的名称将是“source_blob_name”,假设您在 GCS gs://bucket_name/folder1/photo 中有此文件。 jpg - bucket_name 为“bucket_name”,source_blob_name 为“folder1/photo.jpg”
    【解决方案2】:

    您可以创建 Cloud Function 并从 Cloud Storage 中的文件中读取下载数据

    def loader(event, context):
        """Triggered by a change to a Cloud Storage bucket.
        Args:
             event (dict): Event payload.
             context (google.cloud.functions.Context): Metadata for the event.
        """
        try:
            file_name = event['name']
            bucket_name = event['bucket']
    
            client = storage.Client()
    
            bucket = client.get_bucket(bucket_name)
            file_blob = storage.Blob(file_name, bucket)
            data = file_blob.download_as_string().decode()
    
    

    获得数据后,您可以在 BigQuery 中创建表。

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2018-08-18
      • 1970-01-01
      • 2017-08-17
      • 2020-03-04
      • 2017-05-11
      • 1970-01-01
      • 2021-06-07
      • 2019-04-19
      相关资源
      最近更新 更多