在GCP云功能中使用iot_v1

时间:2020-09-09 22:29:31

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

我正在尝试用Python编写GCP云函数,该函数调用用于创建IoT设备的API。最初的挑战似乎是在Cloud Functions中加载适当的模块(特别是iot_v1),以便它可以进行调用。

来自Google的示例Python代码位于https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iot/api-client/manager/manager.py。所需的特定调用显示在“ create_es_device”中。尝试将其重新用于Cloud Function(以下代码)时出现错误,出现“ ImportError:无法从'google.cloud'(未知位置)导入名称'iot_v1'”

有什么想法吗?

import base64
import logging
import json
import datetime
from google.auth import compute_engine
from apiclient import discovery
from google.cloud import iot_v1

def handle_notification(event, context):
    #Triggered from a message on a Cloud Pub/Sub topic.
    #Args:
    #     event (dict): Event payload.
    #     context (google.cloud.functions.Context): Metadata for the event.
    #
    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    logging.info('New device registration info: {}'.format(pubsub_message))
    certData = json.loads(pubsub_message)['certs']
    deviceID = certData['device-id']
    certKey = certData['certificate']
    projectID = certData['project-id']
    cloudRegion = certData['cloud-region']
    registryID = certData['registry-id']
    newDevice = create_device(projectID, cloudRegion, registryID, deviceID, certKey)
    logging.info('New device: {}'.format(newDevice))

def create_device(project_id, cloud_region, registry_id, device_id, public_key):
     # from https://cloud.google.com/iot/docs/how-tos/devices#api_1
     client = iot_v1.DeviceManagerClient()
     parent = client.registry_path(project_id, cloud_region, registry_id)

     # Note: You can have multiple credentials associated with a device.
     device_template = {
     #'id': device_id,
     'id' : 'testing_device',
     'credentials': [{
          'public_key': {
               'format': 'ES256_PEM',
               'key': public_key
          }
     }]
     }
     return client.create_device(parent, device_template)

1 个答案:

答案 0 :(得分:0)

您需要在google-cloud-iot文件中列出requirements.txt项目。

请参见https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iot/api-client/manager/requirements.txt