Return csv 数据作为 IBM Cloud Function 的结果
Return csv data as a result for IBM Cloud Function
我有一个用 Python 为 IBM 云编写的函数。对于以下 python 个词典,return 结果为 json:
return {"billing_for_org": output1, "billing_for_org2:": output2}
有没有办法将此数据 return 保存为 CSV 文件?因此,当我调用 api 时,我可以将数据下载为 CSV 文件吗?
这是我测试的一些示例。让我知道它是否是您要找的。
import sys
import csv
import io
def main(dict):
output = io.StringIO()
my_dict = {"billing_for_org": "0", "billing_for_org2": "0"}
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 调用的。
我将上面的代码作为网络操作函数进行了测试并得到了结果。请注意,扩展在 Url 的末尾显示 http
,这使得函数成为 return Non-Default(Json) 有效载荷。
示例 Url - https://openwhisk.ng.bluemix.net/api/v1/web/demo_dev/hello-world/helloworld.http
已收到回复 -
Body:
billing_for_org,billing_for_org2
0,0
Headers:
Content-Type →text/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
我有一个用 Python 为 IBM 云编写的函数。对于以下 python 个词典,return 结果为 json:
return {"billing_for_org": output1, "billing_for_org2:": output2}
有没有办法将此数据 return 保存为 CSV 文件?因此,当我调用 api 时,我可以将数据下载为 CSV 文件吗?
这是我测试的一些示例。让我知道它是否是您要找的。
import sys
import csv
import io
def main(dict):
output = io.StringIO()
my_dict = {"billing_for_org": "0", "billing_for_org2": "0"}
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 调用的。
我将上面的代码作为网络操作函数进行了测试并得到了结果。请注意,扩展在 Url 的末尾显示 http
,这使得函数成为 return Non-Default(Json) 有效载荷。
示例 Url - https://openwhisk.ng.bluemix.net/api/v1/web/demo_dev/hello-world/helloworld.http
已收到回复 -
Body:
billing_for_org,billing_for_org2
0,0
Headers:
Content-Type →text/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