关于amazon-web-services:玩转AWS六利用Lambda函数获取S3-url写入mysql

51次阅读

共计 686 个字符,预计需要花费 2 分钟才能阅读完成。

实战步骤

样例代码 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.")

正文完
 0