Google Cloud Function-ImportError:无法从"google.cloud"(未知位置)导入名称"pubsub"

问题描述:

我正在部署一个Google Cloud Function,它将使用google.cloud.pubsub_v1启动其他Google Cloud Function,并且出现此错误ImportError: cannot import name 'pubsub' from 'google.cloud' (unknown location)

I am deploying a Google Cloud Function that will kick off other Google Cloud Functions using google.cloud.pubsub_v1 and I'm getting this error ImportError: cannot import name 'pubsub' from 'google.cloud' (unknown location)

我的requirements.txt文件的开头看起来像这样

The beginning of my requirements.txt file looks like this

# Function dependencies, for example:
# package>=version
google-cloud-pubsub
....

main.py脚本的开始看起来像这样:

The beginning of my main.py script looks like this:

import base64
import json
from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(<PROJECT_ID>, <PUBSUB_TOPIC>)

我正在从Google Cloud Source存储库中部署此代码.我已阅读关于我的错误的这篇SO帖子,但该问题似乎关于客户端应用程序中出现的此错误.我的错误是在部署过程中由Google Cloud函数本身生成的.我对Google正在用来运行我的进程的自动创建的VM没有sudo权限,对吗?我应该能够从requirements.txt文件中解决此问题,但是我尝试过的任何方法似乎都无法正常工作.

I am deploying this code from a Google Cloud Source Repository. I have read through this SO post about my error, but that question appears to be about this error arising in a Client application. My error is being generated by the Google Cloud function itself during the deploy process. I don't have sudo rights to the auto-created VM that Google is using to run my process, do I? I should be able to resolve this issue from the requirements.txt file, but nothing I've tried seems to be working.

更令人沮丧的是,当我将相同的代码放入基于Web的Google Function编辑器的"Inline编辑器"中时,没有出现错误.从存储库加载代码时,只会出现此错误.

What's more frustrating is that when I put this same code in the "Inline editor" on the web-based Google Function editor, I don't get an error. I only get this error when loading the code from the repository.

存储库中的当前文件结构如下所示:

The current file structure in the repository looks something like this:

.
├── package
|   ├── main.py
|   ├── script1.py
|   └── script2.py
├── package2
├── ...
└── requirements.txt

由于关于如何解决此导入错误的任何想法?

Any ideas on how to resolve this import error?

您的main.py文件和requirements.txt文件应位于同一目录中,并且该目录也应与您从中部署功能的目录相同.

Your main.py file and requirements.txt file should be in the same directory, and this should also be the same directory you're deploying your function from.

此外, google-cloud 包已被弃用,不应与其他google-cloud-*软件包.您应该将其从requirements.txt文件中删除.

Also, the google-cloud package is deprecated and shouldn't be used with other google-cloud-* packages. You should remove it from your requirements.txt file.