Облачная функция, запускаемая Pubsub - PullRequest
0 голосов
/ 06 августа 2020
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)

Ответы [ 2 ]

0 голосов
/ 07 августа 2020

Решил проблему, изменив кодировку. Я кодировал строковые данные, изменил их на кодировку json данных, и это сработало

0 голосов
/ 06 августа 2020

Это нормально работает. Пожалуйста, попробуйте опубликовать sh сообщение прямо в topi c в пользовательском интерфейсе. Я попытался со следующим сообщением, и он дал результат {"abc":"123456","Def":"udebj"}

введите описание изображения здесь

...