从App Engine运行时Python 3.7调用Cloud Function

时间:2019-02-20 01:21:12

标签: python google-app-engine python-requests google-cloud-functions google-app-engine-python

我有一个运行Python 3.7的App Engine服务,需要通过https.oncall触发器从我的一个Cloud Functions调用并获取响应。

我认为我可以通过以下方式做到这一点:

import logging
from sys import exit

import firebase_admin

import requests

import google.cloud.logging
client = google.cloud.logging.Client()
client.setup_logging()

firebase_admin.initialize_app()

response = requests.post("https://us-central1-myproject.cloudfunctions.net/functionname", data={"foo": "bar"})

if response.status_code != 200:
    exit("Could not call function! :(") # This is happening

logging.info(f"Yay! Here is the result: {response.text}")

# do something else

exit()

但是,我从Cloud Functions获得Request has incorrect Content-Type.

我已经尝试过各种请求语法的变体,例如:data='{"foo": "bar"}'data=json.dumps({"foo": "bar"}),但我能得到的只是Request has incorrect Content-Type.Request has incorrect Content-Type. application/x-www-form-urlencoded

如何正确地将字典附加到我的请求上,以使函数以in the Cloud Function docs所示的application/json形式接收它?

我读过其他文章,建议使用json.dumps()函数会告诉request使用application/json,但是Cloud Functions对此并不满意。

1 个答案:

答案 0 :(得分:1)

您没有为请求设置Content-Type。从requests==2.4.2开始,您可以改用json参数来传递字典并自动设置Content-Type

requests.post(url, json={"foo": "bar"})