python-3.x - 返回 csv 数据作为 IBM Cloud Function 的结果
问题描述
我有一个用 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
推荐阅读
- python - 如何获取打开模式窗口的url
- perl - perl @_ 数组有十个元素限制吗?在将 11 个参数传递给我的 sub 时,第 11 个参数始终是 undef
- api - 如何防止对 API Key 和 API Secret 的 MITM 攻击?
- android - Android 垃圾收集器何时清除我的实例?
- python - 如何在 Django 中将数据从一个列表传输到另一个列表?
- bash - 模拟选项卡以在 bash 脚本中自动填充导航(cd)?
- sql - 如何在保留“,”的同时显示员工姓名而不是员工 ID
- snowflake-cloud-data-platform - 如何查找 Snowflake Task 正在针对哪个仓库运行?
- pandas - 将熊猫数据框中特定单元格的值设置为其他两个单元格的总和
- python - 如何在特定的父 div 类中定位特定的 div 类,python selenium