【问题标题】:Cloud Function Triggered by Pubsub由 Pubsub 触发的云函数
【发布时间】:2020-11-26 18:32:11
【问题描述】:
import base64
import logging

def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         event (dict):  The dictionary with data specific to this type of
         event. The `data` field contains the PubsubMessage message. The
         `attributes` field will contain custom attributes if there are any.
         context (google.cloud.functions.Context): The Cloud Functions event
         metadata. The `event_id` field contains the Pub/Sub message ID. The
         `timestamp` field contains the publish time.
    """
    import base64
    import time
    import json
    import requests
    print(event)

    print("""This Function was triggered by messageId {} published at {}
    """.format(context.event_id, context.timestamp))

    if 'data' in event:
        name = base64.b64decode(event['data']).decode('utf-8')
    else:
        name = 'World'
    print(name)
    print(type(name))    
    print('Hello {}!'.format(name))
    
    
    payload = json.loads(name)
    logging.debug(payload)

我试图执行这是云函数,但我收到一个错误,这可能是因为 json.loads()。如何以 Json 形式获取有效负载

错误:

line 32, in hello_pubsub payload = json.loads(name) File "/opt/python3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/opt/python3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/opt/python3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

  • 产生错误时“name”的值是多少?
  • name 的值 = b'{"abc":"123456","Def":"udebj"} 名称的类型 = @Kolban

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


【解决方案1】:

这工作正常。 请尝试将消息直接发布到 UI 上的主题。 我尝试了以下消息,它给出了输出 {"abc":"123456","Def":"udebj"}

【讨论】:

  • 嗨@Vikram 我正在使用我的用户界面发布味精,但与您不同的是,我收到b'{"abc":"123456","Def":"udebj"} 作为输出。并且 json.loads() 抛出解码错误
  • 能不能帮忙分享一下自己写的云函数
  • 如果您使用的是python3.8,则在requirements.txt中添加请求库如果您使用的是python3.7,则无需更改。
  • 你能分享你的日志截图和输入数据到pubsub主题吗
  • 输入数据:{"abc":"def"}
【解决方案2】:

通过更改编码解决了问题。 我正在对字符串数据进行编码,将其更改为对 json 数据进行编码,并且可以正常工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2020-08-30
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多