【问题标题】:Return csv data as a result for IBM Cloud Function返回 csv 数据作为 IBM Cloud Function 的结果
【发布时间】:2019-05-23 17:26:06
【问题描述】:

我有一个用 Python 为 IBM 云编写的函数。对于以下 python 字典,它以 json 形式返回结果:

return {"billing_for_org": output1, "billing_for_org2:": output2}

有没有办法将此数据作为 CSV 文件返回?所以当我调用 api 时,我可以将数据下载为 CSV 文件?

【问题讨论】:

    标签: python-3.x ibm-cloud ibm-cloud-functions


    【解决方案1】:

    这是我测试的一些示例。让我知道您是否正在寻找它。

    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 操作函数进行了测试并得到了结果。请注意,扩展名在 Url 末尾显示 http,这使得函数返回非默认(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 内容长度 →45 连接 →keep-alive Content-Disposition →attachment;filename=myfilename.csv

    参考 - https://console.bluemix.net/docs/openwhisk/openwhisk_webactions.html#openwhisk_webactionshttps://developer.ibm.com/answers/answers/406943/view.html

    【讨论】:

    • 当我将上述代码作为 Web 操作运行时,我没有下载任何文件?我只是看到这个结果: { "body": "billing_for_org,billing_for_org2\r\n$100,$200\r\n", "headers": { "Content-Disposition": "attachment;filename=myfilename.csv" , "内容类型": "text/csv" } }
    • Url 应该在函数名之后以 .http 结尾。你是用 .json 扩展名吗?。
    猜你喜欢
    • 2021-09-21
    • 1970-01-01
    • 2018-05-19
    • 2010-09-30
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2021-05-07
    • 2021-01-17
    相关资源
    最近更新 更多