问题描述
我有一个运行Python 3.7的App Engine服务,需要通过https.oncall
触发器调用我的一个Cloud Functions并获取响应.
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()
但是,我从Cloud Functions获得Request has incorrect Content-Type.
.
However, I'm getting Request has incorrect Content-Type.
from Cloud Functions.
我已经尝试过各种请求语法的变体,例如:data='{"foo": "bar"}'
和data=json.dumps({"foo": "bar"})
,但是我能得到的只是Request has incorrect Content-Type.
或Request has incorrect Content-Type. application/x-www-form-urlencoded
.
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
.
如何正确地将字典附加到我的请求上,以使函数以application/json
的形式接收字典,如 ?
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?
我读过其他文章,建议使用json.dumps()
函数会告诉request
使用application/json
,但是Cloud Functions对此并不满意.
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.
推荐答案
您没有为您的请求设置Content-Type
.从requests==2.4.2
开始,您可以改用json
参数传递字典并自动设置Content-Type
:
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"})
这篇关于从App Engine运行时Python 3.7调用Cloud Function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!