谷歌云函数 python 脚本创建存储桶 - 不上传文件

时间:2020-12-20 21:07:40

标签: python python-3.x google-cloud-functions

我想要做什么:

  • 运行一些 BigQuery 查询
  • 将结果输出为 JSON 文件
  • 将 JSON 文件上传到 GCS

我想怎么做:

  1. 安装并初始化 Google Cloud SDK:gcloud auth activate-service-account --key-file="gcp-credentials.json"
  2. 启用 API:
gcloud services enable \
    bigquery.googleapis.com \
    cloudbuild.googleapis.com \
    cloudfunctions.googleapis.com \
    cloudscheduler.googleapis.com \
    pubsub.googleapis.com \
    serviceusage.googleapis.com \
    storage-component.googleapis.com
  1. 编写代码:
src
|__data
|__queries
      |__test_query_1.sql
      |__test_query_2.sql
      |__test_query_3.sql
|__scripts
      |__config.py
      |__log.txt
      |__main.py
      |__requirements.txt

要求.txt

google-cloud-bigquery
google-cloud-storage

config.py:

from pathlib import Path

src_dir = Path(__file__).absolute().parent

config_vars = {
    "data_dir": src_dir.parent / "data",
    "queries_dir": src_dir.parent / "queries",
    "bucket": "...",
}

main.py:

import ...
data_dir = config.config_vars["data_dir"]
queries_dir = config.config_vars["queries_dir"]

def main(data, context):
    ...

if __name__ == "__main__":
    main("data", "context")

因此,main.py 脚本获取查询文件夹中的所有查询,运行它们,将它们输出为 JSON,然后将它们上传到名为“test-bucket-20201219”的存储桶。如果存储桶不存在,则创建它。

脚本在本地运行良好,但是当它通过 PubSub 和 Google Scheduler 在 GCP 中部署和调度时,它运行并创建存储桶但不上传文件......我不确定我做错了什么。任何帮助将非常感激。尝试了一切 - 例如允许 PROJECTID@appspot.gserviceaccount.com 将对象添加到存储桶。

记录语句:

2020-12-20 18:43:50,656 | INFO | Uploading test_query_2.json to test-bucket-20201219.
2020-12-20 18:43:50,962 | DEBUG | https://storage.googleapis.com:443 "POST /upload/storage/v1/b/test-bucket-20201219/o?uploadType=multipart HTTP/1.1" 200 776
2020-12-20 18:43:50,963 | INFO | Uploading test_query_3.json to test-bucket-20201219.
2020-12-20 18:43:51,238 | DEBUG | https://storage.googleapis.com:443 "POST /upload/storage/v1/b/test-bucket-20201219/o?uploadType=multipart HTTP/1.1" 200 776
2020-12-20 18:43:51,239 | INFO | Uploading test_query_1.json to test-bucket-20201219.
2020-12-20 18:43:51,466 | DEBUG | https://storage.googleapis.com:443 "POST /upload/storage/v1/b/test-bucket-20201219/o?uploadType=multipart HTTP/1.1" 200 775

1 个答案:

答案 0 :(得分:0)

感谢每个人的帮助 - 不知何故得到了它。我想我错过了第一次运行/部署云函数时自动生成的存储桶 (staging.PROJECT_ID.appspot.com)。此外,由于我不想将凭据与函数的存储库一起存储,因此我使用 --service-account 标志以 PROJECT_ID@appspot.gserviceaccount.com...tbh 的形式从 gcloud 部署了该函数,我不完全确定如果我所做的正确但对我有用。

Unable to deploy google cloud functions