Write CSV data to AWS-S3 with AWS-Lambda + Python

Write CSV data to AWS-S3 with AWS-Lambda + Python

Introduction

`Although it is an article on Mac environment, the procedure is the same for Windows environment. Please read and try the environment-dependent part. ``

Purpose

After reading this article to the end, you will be able to:

No. Overview keyword
1 coding Python, boto3
2 Lambda settings Lambda

Execution environment

environment Ver.
macOS Catalina 10.15.3
Python 3.7.3
boto3 1.11.17

Source code

I think that understanding will deepen if you read while actually following the implementation contents and source code. Please use it by all means.

GitHub

Related articles

Features of AWS-Lambda

This service is a pay-as-you-go system. Please note.

-Features -Price

Overall flow

  1. Write Python code
  2. Create a Lambda function
  3. Set environment variables

1. Write Python code

coding

app/lambda_function.py


"""app/lambda_function.py
"""

import os
import sys
from datetime import datetime, timedelta, timezone

from boto3.session import Session


def _localtime(time_zone):
    """_localtime
    """
    return datetime.now(timezone.utc)+timedelta(hours=int(time_zone))


def _write_to_s3(param):
    """_write_to_s3
    """
    access_key_id = param.get('aws_access_key_id')
    secret_access_key = param.get('aws_secret_access_key')
    region_name = param.get('aws_region_name')
    bucket_name = param.get('s3_bucket_name')
    file_name_format = param.get('s3_file_name_format')
    encode = param.get('s3_encode')
    data = param.get('data')

    session = Session(aws_access_key_id=access_key_id,
                      aws_secret_access_key=secret_access_key,
                      region_name=region_name)
    s3 = session.resource('s3')
    bucket = s3.Bucket(bucket_name)  # pylint: disable=no-member

    fname = '{}.csv'.format(_localtime(time_zone=9).strftime(file_name_format))
    print('fname: {}'.format(fname))
    obj = bucket.Object(fname)

    try:
        obj.put(
            Body=data.encode(encode, 'ignore'),
            ContentEncoding=encode,
            ContentType='text/csv'
        )
    except AttributeError as e:
        print(e)
        sys.exit()


def lambda_handler(event, context):
    """lambda_handler
    """
    print('event: {}'.format(event))
    print('context: {}'.format(context))

    param = {
        'aws_access_key_id': os.getenv('S3_ACCESS_KEY_ID', ''),
        'aws_secret_access_key': os.getenv('S3_SECRET_ACCESS_KEY', ''),
        'aws_region_name': os.getenv('S3_REGION_NAME', ''),
        's3_bucket_name': os.getenv('S3_BUCKET_NAME', ''),
        's3_file_name_format': os.getenv('S3_FILE_NAME_FORMAT', ''),
        's3_encode': os.getenv('S3_ENCODE', ''),
        'data': _localtime(time_zone=0).strftime('%Y-%m-%dT%H:%M:%S+00:00')
    }
    _write_to_s3(param=param)

    return {
        'status_code': 200
    }


if __name__ == '__main__':
    lambda_handler(event=None, context=None)

2. Create a Lambda function

Perform up to zip upload by referring to the article AWS-Lambda + Python + Cron to perform web scraping regularly

3. Set environment variables

Environment variable

  1. Set from Edit in the Environment Variables section
Key value
S3_ACCESS_KEY_ID {aws_access_key_id}
S3_SECRET_ACCESS_KEY {aws_secret_access_key}
S3_REGION_NAME {region_name}
S3_BUCKET_NAME {bucket}
S3_FILE_NAME_FORMAT e.g. release/%Y-%m/%Y-%m-%d
S3_ENCODE e.g. cp932

`{} is different for each environment. ``

Recommended Posts

Write CSV data to AWS-S3 with AWS-Lambda + Python
Write to csv with Python
[Python] Write to csv file with Python
[Python] A memo to write CSV vertically with Pandas
Output to csv file with Python
Convert Excel data to JSON with python
Convert FX 1-minute data to 5-minute data with Python
[Part1] Scraping with Python → Organize to csv!
Compress python data and write to sqlite
Data analysis with python 2
How to create sample CSV data with hypothesis
How to read a CSV file with Python 2/3
Scraping tabelog with python and outputting to CSV
[Data science basics] I tried saving from csv to mysql with python
[Write to map with plotly] Dynamic visualization with plotly [python]
Csv tinkering with python
I want to write to a file with Python
Data analysis with Python
Summary of how to read numerical data with python [CSV, NetCDF, Fortran binary]
Convert csv, tsv data to matrix with python --using MovieLens as an example
How to scrape image data from flickr with python
I tried to touch the CSV file with Python
Reading Note: An Introduction to Data Analysis with Python
How to convert JSON file to CSV file with Python Pandas
Write multiple records to DynamoDB with Lambda (Python, JavaScript)
A program to write Lattice Hinge with Rhinoceros with Python
For those who want to write Python with vim
Process csv data with python (count processing using pandas)
[Python-pptx] Output PowerPoint font information to csv with python
I tried to analyze J League data with Python
Sample data created with python
Connect to BigQuery with Python
Extract Twitter data with CSV
Connect to Wikipedia with Python
Get Youtube data with python
Switch python to 2.7 with alternatives
Download csv file with python
Read json data with python
I want to be able to analyze data with Python (Part 3)
I tried to make various "dummy data" with Python faker
I want to be able to analyze data with Python (Part 1)
20200329_Introduction to Data Analysis with Python Second Edition Personal Summary
I want to be able to analyze data with Python (Part 4)
I want to be able to analyze data with Python (Part 2)
Stylish technique for pasting CSV data into Excel with Python
Python code for writing CSV data to DSX object storage
[Introduction to Python] Combine Nikkei 225 and NY Dow csv data
Get additional data to LDAP with python (Writer and Reader)
A python script that converts Oracle Database data to csv
[Introduction to Python] How to get data with the listdir function
How to write offline real-time Solving E05 problems with Python
How to write a Python class
[Python] How to FFT mp3 data
Python: How to use async with
Link to get started with python
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate Facebook with Python
How to deal with imbalanced data
How to deal with imbalanced data
[Python] Get economic data with DataReader