简体   繁体   English

如何从 Google Cloud 函数返回 JSON

[英]How to I return JSON from a Google Cloud Function

How do I return JSON from a HTTP Google Cloud Function in Python?如何从 Python 中的 HTTP Google Cloud 函数返回 JSON? Right now I have something like:现在我有类似的东西:

import json

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

This correctly returns JSON, but the Content-Type is wrong (it's text/html instead).这正确返回 JSON,但Content-Type是错误的(而是text/html )。

Cloud Functions has Flask available under the hood, so you can use it's jsonify function to return a JSON response. Cloud Functions 在底层提供了Flask ,因此您可以使用它的jsonify函数来返回 JSON 响应。

In your function:在您的功能中:

from flask import jsonify

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

This will return a flask.Response object with the application/json Content-Type and your data serialized to JSON.这将返回一个带有 application/json Content-Type和序列化为 JSON 的dataflask.Response对象。

You can also do this manually if you prefer to avoid using Flask:如果您不想使用 Flask,也可以手动执行此操作:

import json

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

You don't need Flask per se你不需要 Flask 本身

import json

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

Make 200 whatever response code is suitable, eg.制作 200 任何合适的响应代码,例如。 404, 500, 301, etc. 404、500、301等

If you're replying from a HTML AJAX request如果您从 HTML AJAX 请求回复

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

to return an error instead for the AJAX request为 AJAX 请求返回错误

return json.dumps({'error': True}), 404, {'ContentType': 'application/json'}

For me, json.dumps() did not work in the cloud function.对我来说, json.dumps() 在云函数中不起作用。 It worked only in my local server.它只在我的本地服务器上工作。 So, I had to build the json by myself:所以,我不得不自己构建json:

    headers= {
        'Access-Control-Allow-Origin': '*',
        'Content-Type':'application/json'
        }
    id1= "1234567"
    var1= "variable 1"
    text = '{"id1":"'+id1+'","var1":"'+var1+'"}'
    return (text, 200, headers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM