我有一个用 Python 为 IBM 云编写的函数。对于以下 python 字典,它以 json 形式返回结果:
return {"billing_for_org": output1, "billing_for_org2:": output2}
有没有办法将此数据作为 CSV 文件返回?那么当我调用 api 时,我可以将数据下载为 CSV 文件吗?
我有一个用 Python 为 IBM 云编写的函数。对于以下 python 字典,它以 json 形式返回结果:
return {"billing_for_org": output1, "billing_for_org2:": output2}
有没有办法将此数据作为 CSV 文件返回?那么当我调用 api 时,我可以将数据下载为 CSV 文件吗?
这是我测试的一些样本。让我知道它是否是您要找的。
import sys
import csv
import io
def main(dict):
output = io.StringIO()
my_dict = {"billing_for_org": "$100", "billing_for_org2": "$200"}
w = csv.DictWriter(output, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
return {"body": output.getvalue(),
"headers": {'Content-Type': 'text/csv','Content-Disposition':'attachment;filename=myfilename.csv'}}
我不确定您是如何将函数调用为 Rest API 或 Web Action。
我将上面的代码作为 web 操作函数进行了测试并得到了结果。请注意,扩展http
在 Url 的末尾说,这使得函数返回非默认(Json)有效负载。
示例网址 - https://openwhisk.ng.bluemix.net/api/v1/web/demo_dev/hello-world/helloworld.http
收到回复 -
身体:
billing_for_org,billing_for_org2
100 美元,200 美元
标题:
内容类型→文本/csv;charset=UTF-8 Content-Length →45 Connection →keep-alive Content-Disposition →attachment;filename=myfilename.csv
参考 - https://console.bluemix.net/docs/openwhisk/openwhisk_webactions.html#openwhisk_webactions。 https://developer.ibm.com/answers/answers/406943/view.html