Calling Cloud Function from App Engine runtime Python 3.7 [duplicate]

冷暖自知 提交于 2020-05-15 09:08:10

问题


I have an App Engine service, running Python 3.7, that needs to call and get a response from one of my Cloud Functions via the https.oncall trigger.

I thought I could do so with the following:

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()

However, I'm getting Request has incorrect Content-Type. from Cloud Functions.

I've tried multiple variations on the request syntax such as: data='{"foo": "bar"}' and data=json.dumps({"foo": "bar"}) but all I can get back is either Request has incorrect Content-Type. or Request has incorrect Content-Type. application/x-www-form-urlencoded.

How do I properly attach my dictionary to my request so that the function receives it in the form of application/json as noted in the Cloud Function docs?

I've read other posts that suggest using the json.dumps() function will tell request to use application/json but Cloud Functions wasn't happy about it.


回答1:


You're not setting the Content-Type for your request. Starting with requests==2.4.2, you can use the json parameter instead to pass a dictionary and automatically set the Content-Type:

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


来源:https://stackoverflow.com/questions/54777411/calling-cloud-function-from-app-engine-runtime-python-3-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!