首页 > 解决方案 > 部署云功能时google Bigquery导入错误

问题描述

我有一个 python Cloud 函数代码,它从 GCS 读取 .txt 文件,对其进行解析并将行写入 bigquery。当我尝试从我的 MacOS 将此云功能部署到 Google 云中时,它给了我以下错误

我已验证在我的 GCP 项目中启用了 Bigquery API。

gcloud 函数部署 sql_upload --runtime python37 --trigger-bucket test-bucket --entry-point load_sql

Deploying function (may take a while - up to 2 minutes)...failed.                                                                                                                                          
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. Error message: Code in file main.py can't be loaded.
Detailed stack trace: Traceback (most recent call last):
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 305, in check_or_load_user_function
    _function_handler.load_user_function()
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 184, in load_user_function
    spec.loader.exec_module(main)
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed  File "/user_code/main.py", line 24, in <module>
    from google.cloud import bigquery
ImportError: cannot import name 'bigquery' from 'google.cloud' (unknown location)

标签: google-cloud-platformgoogle-bigquery

解决方案


Python 中的依赖项使用 pip 进行管理,并在名为 requirements.txt 的元数据文件中表示。此文件必须与包含您的函数代码的 main.py 文件位于同一目录中。

如果此代码在您的计算机上运行,​​则只需通过以下方式创建 requirements.txt 文件:

pip freeze > requirements.txt

否则,您首先必须安装 bigquery 的依赖项,然后创建需求文件:

pip install --upgrade google-cloud-bigquery
pip freeze > requirements.txt

请参阅文档 https://cloud.google.com/functions/docs/writing/specifying-dependencies-python https://cloud.google.com/bigquery/docs/reference/libraries#client-libraries-install-python


推荐阅读