【问题标题】:Use iot_v1 in a GCP Cloud Function在 GCP 云函数中使用 iot_v1
【发布时间】:2020-12-28 09:37:54
【问题描述】:

我正在尝试用 Python 编写一个 GCP 云函数,该函数调用 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”中。尝试将其重新用于云函数(下面的代码)错误“ImportError: cannot import name 'iot_v1' from 'google.cloud' (unknown location)”

有什么想法吗?

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)

【问题讨论】:

  • 你能给我们看看你的requirements.txt文件吗?

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


【解决方案1】:

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

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

【讨论】:

  • 成功了!谢谢!!
  • 很高兴有帮助,如果它解决了您的问题,请不要忘记接受答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 2021-06-17
  • 2021-10-06
  • 1970-01-01
相关资源
最近更新 更多