玩转AWS(六):利用Lambda函数获取S3 url写入mysql

实战步骤



样例代码 gets3url.py

import boto3
import mysql.connector

s3Client = boto3.client('s3')
mydb = mysql.connector.connect(
    host="xxx",
    user="xxx",
    password="xxx",
    database="xxx",
    port="xxx"
)

def lambda_handler(event, context):
    #Get our bucket and file name
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    #Get live_id from s3 object key
    live_id = key.split("/")[2]
    print("live_id: {}".format(live_id) )

    # S3 object url
    obj_url = "https://" + bucket + ".s3.xxx.amazonaws.com/" + key
    print("obj_url: {}".format(obj_url))

    # Insert into mysql
    mycursor = mydb.cursor()
    sql = "INSERT INTO s3_bucket_obj (%s) VALUES (%s);"
    mycursor.execute(sql, (obj_url, live_id))

    mydb.commit()
    print(mycursor.rowcount, "record inserted.")

你可能感兴趣的:(玩转AWS(六):利用Lambda函数获取S3 url写入mysql)