如何使用 Python 在 Lambda 中创建 CSV?

How do I create a CSV in Lambda using Python?

我想使用 Python 在 Lambda 中创建一个保存在 CSV 文件中的报告。所以你会发现函数的代码:

import boto3
import datetime
import re

def lambda_handler(event, context):

    client = boto3.client('ce')

    now = datetime.datetime.utcnow()
    end = datetime.datetime(year=now.year, month=now.month, day=1)

    start = end - datetime.timedelta(days=1)
    start = datetime.datetime(year=start.year, month=start.month, day=1)

    start = start.strftime('%Y-%m-%d')
    end = end.strftime('%Y-%m-%d')


    response = client.get_cost_and_usage(
        TimePeriod={
            'Start': "2019-02-01",
            'End':  "2019-08-01"
        },
        Granularity='MONTHLY',
        Metrics=['BlendedCost'],
        GroupBy=[
            {
                'Type': 'TAG',
                'Key': 'Project'
            },
        ]
    )

如何从中创建 CSV 文件?

这是使用 Python 在 Lambda 中创建 CSV 文件的示例函数:

假设变量'response'具有为您创建报告所需的数据,以下代码将帮助您在lambda函数的/tmp文件夹中创建一个临时CSV文件:

import csv
temp_csv_file = csv.writer(open("/tmp/csv_file.csv", "w+"))
# writing the column names
temp_csv_file.writerow(["Account Name", "Month", "Cost"])

# writing rows in to the CSV file
for detail in response:
    temp_csv_file.writerow([detail['account_name'],
                            detail['month'],
                            detail['cost']
                            ])

创建 CSV 文件后,您可以将其上传到 S3 并通过电子邮件发送或使用以下代码将其共享为 link:

client = boto3.client('s3')
client.upload_file('/tmp/csv_file.csv', BUCKET_NAME,'final_report.csv')

要记住的要点:

  1. /tmp是一个大小为512MB的目录存储,可以用来存放一些内存/临时文件
  2. 您不应依赖此存储来维护后续 lambda 函数的状态。

Repakula Srushith 的上述回答是正确的,但由于文件未关闭,因此将创建一个空的 csv。您可以将代码更改为

f = open("/tmp/csv_file.csv", "w+")
temp_csv_file = csv.writer(f) 
temp_csv_file.writerow(["Account Name", "Month", "Cost"])

# writing rows in to the CSV file
for detail in response:
    temp_csv_file.writerow([detail['account_name'],
                            detail['month'],
                            detail['cost']
                            ])
f.close()