实施由GCS最终确定触发发布到pubsub的云功能

时间:2018-12-06 05:57:02

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

我一直在尝试用Python编写和部署云功能。 (由于文档混乱且更改速度相对较快,因此放弃了node.js)

用于将消息发布到发布/订阅主题,当文件完成上传到Google云存储桶(“完成”)时触发。

我用来部署该功能的代码是

gcloud functions deploy hello_gcs_generic --runtime python37 --trigger-resource bucketcfpubsub

我一直在尝试使用this script provided by Google

import time

from google.cloud import pubsub_v1

project_id = "bucketcfpubsub"
topic_name = "projects/bucketcfpubsub/topics/pubsub"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)

def callback(message_future):
# When timeout is unspecified, the exception method waits indefinitely.
if message_future.exception(timeout=30):
    print('Publishing message on {} threw an Exception {}.'.format(
        topic_name, message_future.exception()))
else:
    print(message_future.result())

for n in range(1, 10):
    data = u'Message number {}'.format(n)
# Data must be a bytestring
    data = data.encode('utf-8')
# When you publish a message, the client returns a Future.
    message_future = publisher.publish(topic_path, data=data)
    message_future.add_done_callback(callback)

print('Published message IDs:')

# We must keep the main thread from exiting to allow it to process
# messages in the background.
while True:
    time.sleep(60)

我在Google Cloud Console中收到这些错误的原因

ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function load error: 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_v1beta2/worker.py", line 256, in check_or_load_user_function
    _function_handler.load_user_function()
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 166, 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 "<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 3, in <module>
    from google.cloud import pubsub_v1
ImportError: cannot import name 'pubsub_v1' from 'google.cloud' (unknown location)

按照these two帖子中的说明,我从helloworld代码示例中复制了requirements.txt,其中仅包含

google-cloud-error-reporting==0.30.0

并更新了其他云功能,例如bigquery,存储和日志记录。然后我得到了这些错误:

ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function load error: 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_v1beta2/worker.py", line 256, in check_or_load_user_function
    _function_handler.load_user_function()
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 166, 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 3, in <module>
from google.cloud import pubsub_v1`

,我也找到了[此线程](ImportError: cannot import name 'pubsub_v1' from 'google.cloud' (unknown location),但我不太明白解决方案是什么,我尝试用google-cloud-pubsub == 0.38.0代替pubsub_v1,但没有帮助。我收到此错误:

Deploying function (may take a while - up to 2 minutes)...failed.
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function load error: 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_v1beta2/worker.py", line 256, in check_or_load_user_function
    _function_handler.load_user_function()
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions_v1beta2/worker.py", line 166, in load_user_function
    spec.loader.exec_module(main)
  File "<frozen importlib._bootstrap_external>", line 724, in exec_module
  File "<frozen importlib._bootstrap_external>", line 860, in get_code
  File "<frozen importlib._bootstrap_external>", line 791, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/user_code/main.py", line 3

此外,如果Google将pubsub更新到新版本后代码会中断,这似乎不是可持续的解决方案?

因此,我非常初学者,很迷失,但我希望本文档可以对您有所帮助。

更新:

似乎pubsub和pubsub_v1都可以使用,虽然不确定有什么区别。

@dustin我做了一个pip install -r requirements.txt,最终匹配了您提供的内容。 我还注意到在将函数部署为“ hello-gcs-generic”时出错,应将其更改为“ callback”。

python代码现在在本地运行良好,但是使用上述代码(OP中的第一行代码)将其部署到云中始终会返回此错误

ERROR: (gcloud.functions.deploy) OperationError: code=3, messa
ge=Function load error: Error: function load attempt timed out
.

2 个答案:

答案 0 :(得分:0)

您需要将google-cloud-pubsub添加到requirements.txt文件中,而不是添加到main.py文件中。它应该看起来像这样:

google-cloud-error-reporting==0.30.0
google-cloud-pubsub==0.38.0

答案 1 :(得分:0)

有一个simpler Python quickstart example可以满足您的需求。 ;-)

您引用的示例更高级。它显示了如何发布带有错误处理的消息。高级示例中的while(True): sleep(60)行可以使主线程保持活动状态,除非发出Ctrl+C或其等效命令以停止程序运行。之所以有此sleep函数,是因为我们可以等待发布期货上的回调调用完成,而不必在发布调用后立即退出程序。再次,对于您要学习如何使用具有Cloud Functions的Cloud Pub / Sub而言,这可能有点太复杂了。我建议不要使用高级示例,而使用快速入门示例。

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"

publisher = pubsub_v1.PublisherClient()
# The `topic_path` method creates a fully qualified identifier
# in the form `projects/{project_id}/topics/{topic_name}`
topic_path = publisher.topic_path(project_id, topic_name)

for n in range(1, 10):
    data = u'Message number {}'.format(n)
    # Data must be a bytestring
    data = data.encode('utf-8')
    # When you publish a message, the client returns a future.
    future = publisher.publish(topic_path, data=data)
    print('Published {} of message ID {}.'.format(data, future.result()))

print('Published messages.')