我正在嘗試創建一個 Lambda 函式,它將自動清除 S3 存盤桶中的 csv 檔案。S3 存盤桶每 500 萬次接收檔案,因此我為 Lambda 函式創建了一個觸發器。為了清理 csv 檔案,我將使用 pandas 庫來創建一個資料框。我已經安裝了一個熊貓層。創建資料框時,會出現錯誤訊息。這是我的代碼:
import json
import boto3
import pandas as pd
from io import StringIO
#call s3 bucket
client = boto3.client('s3')
def lambda_handler(event, context):
#define bucket_name and object _name
bucket_name = event['Records'][0]['s3']['bucket']['name']
object_name = event['Records'][0]['s3']['object']['key']
#create a df from the object
df = pd.read_csv(object_name)
這是錯誤訊息:
[ERROR] FileNotFoundError: [Errno 2] No such file or directory: 'object_name'
在 Cloudwatch 上,它還說:
OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k
有沒有人遇到過同樣的問題?提前感謝您的所有幫助!
uj5u.com熱心網友回復:
在使用 pandas 之前,您必須使用 s3 客戶端從 s3 下載檔案。就像是:
response = client.get_object(Bucket=bucket_name, Key=object_name)
df = pd.read_csv(response["Body"])
您必須確保 lambda 具有訪問 s3 存盤桶的正確權限。
uj5u.com熱心網友回復:
更改此行:
df = pd.read_csv("object_name")
對此:
df = pd.read_csv(object_name)
uj5u.com熱心網友回復:
錯誤原因
object_name只是 s3 物件相對于存盤桶的相對路徑(鍵),沒有它就沒有意義,bucket_name因此當您嘗試讀取您得到的 csv 檔案時FileNotFoundError
錯誤的解決方案
為了正確參考 s3 物件,您必須從bucket_name和構造完全限定的 s3 路徑object_name。另請注意,物件鍵有一些帶引號的字符,因此在構造完全限定路徑之前,您必須取消參考它們。
from urllib.parse import unquote_plus
def lambda_handler(event, context):
#define bucket_name and object _name
bucket_name = event['Records'][0]['s3']['bucket']['name']
object_name = event['Records'][0]['s3']['object']['key']
#create a df from the object
filepath = f's3://{bucket_name}/{unquote_plus(object_name)}'
df = pd.read_csv(filepath)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485796.html
標籤:Python 熊猫 亚马逊网络服务 亚马逊-s3 aws-lambda
