[英]ImportError: cannot import name 'pubsub_v1' from 'google.cloud' (unknown location)
[英]Google Cloud Function - ImportError: cannot import name 'pubsub' from 'google.cloud' (unknown location)
我正在部署一個谷歌雲函數,它將使用google.cloud.pubsub_v1
啟動其他谷歌雲函數,我收到此錯誤ImportError: cannot import name 'pubsub' from 'google.cloud' (unknown location)
我的requirements.txt文件的開頭是這樣的
# Function dependencies, for example:
# package>=version
google-cloud-pubsub
....
我的 main.py 腳本的開頭如下所示:
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 Repository 部署此代碼。 我已經通讀了這篇關於我的錯誤的SO 帖子,但這個問題似乎是關於客戶端應用程序中出現的這個錯誤。 我的錯誤是在部署過程中由 Google Cloud 函數本身生成的。 我對 Google 用來運行我的進程的自動創建的 VM 沒有sudo
權限,對嗎? 我應該能夠從requirements.txt
文件解決這個問題,但我嘗試過的任何東西似乎都不起作用。
更令人沮喪的是,當我在基於網絡的 Google 函數編輯器的“內聯編輯器”中放置相同的代碼時,我沒有收到錯誤消息。 我只在從存儲庫加載代碼時收到此錯誤。
存儲庫中的當前文件結構如下所示:
.
├── package
| ├── main.py
| ├── script1.py
| └── script2.py
├── package2
├── ...
└── requirements.txt
由於我在這個 SO Question 中遇到的問題,我將 main.py 移到了一個包中
關於如何解決此導入錯誤的任何想法?
你的main.py
文件和requirements.txt
文件應該在同一個目錄中,這也應該是你部署函數的同一個目錄。
此外, google-cloud
包已棄用,不應與其他google-cloud-*
包一起使用。 您應該將它從您的requirements.txt
文件中刪除。
要安裝google-cloud
庫,您需要執行
pip install google-cloud-storage
正如在官方 Google Cloud 文檔中看到的那樣,所以不要安裝google-cloud-pubsub
。
盡管如此,您還是像以前一樣導入了 pubsub 包
from google.cloud import pubsub_v1
同樣, 此處的官方 Google Cloud 文檔中有一個專用於 pubsub_v1 庫的頁面,其中顯示了以下示例:
import time
from google.cloud import pubsub_v1
# TODO project_id = "Your Google Cloud Project ID"
# TODO subscription_name = "Your Pub/Sub subscription name"
subscriber = pubsub_v1.SubscriberClient()
# The `subscription_path` method creates a fully qualified identifier
# in the form `projects/{project_id}/subscriptions/{subscription_name}`
subscription_path = subscriber.subscription_path(
project_id, subscription_name)
def callback(message):
print('Received message: {}'.format(message))
message.ack()
subscriber.subscribe(subscription_path, callback=callback)
# The subscriber is non-blocking. We must keep the main thread from
# exiting to allow it to process messages asynchronously in the background.
print('Listening for messages on {}'.format(subscription_path))
while True:
time.sleep(60)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.