读取s3事件触发的csv文件

时间:2017-10-24 08:49:16

标签: python csv amazon-s3 serverless-framework

我想读取由s3事件触发的csv文件,换句话说,当csv文件上传到s3时,我的lambda函数将读取此文件并发送包含信息和内容的电子邮件。当没有读取csv文件时,我的代码工作正常,但每当我放入阅读部分,我都无法收到邮件。 我正在使用无服务器框架v - 1.22.0 **和** python 2.7。

这是我的代码:

def csvfile(event, context):
    s3 = boto3.client('s3')
    email_from = '****@****.com'
    email_to = '****@*****.com'
    email_subject = 'new file is uploaded'
    for record in event['Records']:
        filename = record['s3']['object']['key']
        filesize = record['s3']['object']['size']
        source = record['requestParameters']['sourceIPAddress']
        eventTime = record['eventTime']    
    with open(str(filename), 'rb') as csvfile:  
        spamreader = csv.reader(csvfile, delimiter='|')
        for row in spamreader:
            print row 

    email_body = "File Name :" + filename + "\n" + "File Size :" + 
    str(filesize) + "\n" +  "Upload Time :" + eventTime + "\n" + "User 
    Details :" + source + "\n" + "content of the csv file :" + row 
    ses = boto3.client('ses')
    ses.send_email(Source = email_from,
                Destination = {'ToAddresses': [email_to,],}, 
                    Message = {'Subject': {'Data': email_subject}, 'Body':
                              {'Text' : {'Data': email_body}}}
                          )
    print('Function execution Completed !!!')

这是我的serverless.yml文件:

service: aws-python # NOTE: update this with your service name

provider:
  name: aws
  runtime: python2.7
  stage: dev
  region: us-east-1
  iamRoleStatements:
        - Effect: "Allow"
          Action:
              - s3:*
              - "ses:SendEmail"
              - "ses:SendRawEmail"
              - "s3:PutBucketNotification"
          Resource: "*"

functions:
  csvfile:
    handler: handler.csvfile
    description: send mail whenever a csv file is uploaded on S3 
    events:
      - http:
          path: ''
          method: get
      - s3:
          bucket: mine2
          event: s3:ObjectCreated:*
          rules:
            - suffix: .csv

0 个答案:

没有答案