从Django视图调用Google Cloud函数

问题描述 投票:0回答:1

我创建了可通过HTTP调用的Google Cloud函数。该功能的访问仅限于服务帐户。

如果我有一个Django View,它应该调用此函数并期待响应?

这是我尝试过的

1)在启动Django之前,我设置了环境变量

export GOOGLE_APPLICATION_CREDENTIALS

2)我尝试使用独立代码调用该函数,但很快意识到这没用,因为在此之后我无法弄清楚下一步。

from google.oauth2 import service_account
from apiclient.http import call

SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'credentials/credentials.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

Google的文档确实为您提供了有关API的文档,但是没有示例代码说明如何调用方法或在Python代码中导入什么以及调用这些方法的方式。

您如何通过服务帐户授权将带有JSON数据的POST请求发送到Cloud Function?

**编辑几个小时后,我进行了一些进一步的挖掘,并部分地弄清了这一点。

from google.oauth2 import service_account

import googleapiclient.discovery
import json
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'credentials/credentials.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

cloudfunction = googleapiclient.discovery.build('cloudfunctions', 'v1', credentials=credentials)
#projects/{project_id}/locations/{location_id}/functions/{function_id}.
path='some project path'
data='some data in json that works when invoked through the console'
data=json.dumps(data)
a=cloudfunction.projects().locations().functions().call(name=path, body=data).execute()

我现在遇到另一个错误。

 Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'description': 'Invalid JSON payload received. Unknown name "": Root element must be a message.'}]}]">

我找不到与此有关的任何文档。 JSON应该如何形成?

使JSON像{"message":{my actual payload}}一样无效。

我创建了可通过HTTP调用的Google Cloud函数。该功能的访问仅限于服务帐户。如果我有应该调用此功能的Django视图,...

django google-cloud-platform google-cloud-functions google-api-client
1个回答
0
投票

可以找到所需的文档here

© www.soinside.com 2019 - 2024. All rights reserved.