如何从Google Cloud Function返回JSON

时间:2018-11-12 23:54:16

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

如何使用Python从HTTP Google Cloud Function返回JSON?现在我有类似的东西:

import json

def my_function(request):
    data = ...
    return json.dumps(data)

这可以正确返回JSON,但是Content-Type是错误的(而是text/html)。

3 个答案:

答案 0 :(得分:3)

Cloud Functions在后台使用Flask,因此您可以使用它的jsonify函数返回JSON响应。

在您的requirements.txt文件中,添加flask

flask==1.0.2

在您的职能中:

from flask import jsonify

def my_function(request):
    data = ...
    return jsonify(data)

这将返回一个flask.Response对象,其中包含application / json Content-Type,并且您的data序列化为JSON。

答案 1 :(得分:2)

您本身就不需要Flask

'Source/Robot1' already exists and is not a valid git repo

使200合适的任何响应代码,例如404、500、301等

如果您是从HTML AJAX请求中回复

import json

def my_function(request):
    data = ...
    return json.dumps(data), 200, {'ContentType': 'application/json'}

为AJAX请求返回错误

return json.dumps({'success': True, 'data': data}), 200, {'ContentType': 'application/json'}

答案 2 :(得分:0)

对我来说,json.dumps()在云函数中不起作用。它仅在我的本地服务器上有效。因此,我必须自己构建json:

const [len, setLen] = useState(0);

useEffect(() => {
  if (objects.length < len) {
    // Your code
  }

  setLen(objects.length);
}, [objects.length]);