[英]Access file from one folder of a bucket to another folder of the same bucket in AWS S3
[英]How to move a File from One folder to Another Folder in the same AWS S3 bucket using Lambda?
我正在嘗試在 S3 存儲桶中的文件創建事件中自動將文件從一個文件夾移動到同一 S3 存儲桶中的另一個文件夾。
我希望使用 Lambda 函數的觸發器來執行此操作,但我覺得 Lambda 在根目錄級別觸發並且不能在文件夾級別使用它。
例子:
Bucket Name: my-only-s3-bucket
Source Folder: s3://my-only-s3-bucket/Landing
Target Folder: s3://my-only-s3-bucket/Staging
要求:
當文件被創建或上傳到源文件夾: s3://my-only-s3-bucket/Landing
時,它應該自動移動到s3://my-only-s3-bucket/Staging
,無需任何人工干預
如何做到這一點?
我希望使用 Lambda 函數的觸發器來做到這一點,但我覺得,Lambda 在根目錄級別觸發,不能在文件夾級別使用它。
這不是真的。 S3 沒有文件夾的概念。 您可以使用過濾器前綴,即prefix -> "Landing/"
和/或后綴(例如“.jpg”)在任何“級別”觸發。
S3 觸發器將調用 lambda 並使用新對象作為輸入傳遞事件。 然后只需使用您熟悉的任何語言,並使用來自任何可用AWS 開發工具包(.Net、Java、python 等)的 s3 copy 內置函數復制到目標。
例子:
def object_copied?(
s3_client,
source_bucket_name,
source_key,
target_bucket_name,
target_key)
return true if s3_client.copy_object(
bucket: target_bucket_name,
copy_source: source_bucket_name + '/' + source_key,
key: target_key
)
rescue StandardError => e
puts "Error while copying object: #{e.message}"
end
我認為相對路徑的概念可以解決您的問題。 這是使用名為s3pathlib的庫解決您的問題的代碼片段,這是一個面向目標的 s3 文件系統接口。
# import the library
from s3pathlib import S3Path
# define source and target folder
source_dir = S3Path("my-only-s3-bucket/Landing/")
target_dir = S3Path("my-only-s3-bucket/Staging/")
# let's say you have a new file in Landing folder, the s3 uri is
s3_uri = "s3://my-only-s3-bucket/Landing/my-subfolder/data.csv"
# I guess you want to cut the file to the new location and delete the original one
def move_file(p_file, p_source_dir, p_target_dir):
# validate if p_file is inside of p_source_dir
if p_file.uri.startswith(p_source_dir.uri):
raise ValueError
# find new s3 path based on the relative path
p_file_new = S3Path(
p_target_dir, p_file.relative_to(p_source_dir)
)
# move
p_file.move_to(p_file_new)
# if you want copy you can do p_file.copy_to(p_file_new)
# then let's do your work
if __name__ == "__main__":
move_file(
p_file=S3Path.from_s3_uri(s3_uri),
p_source_dir=source_dir,
p_target_dir=target_dir,
)
如果你想要更高級的路徑操作,你可以參考這個文檔。 而S3Path.change(new_abspath, new_dirpath, new_dirname, new_basename, new_fname, new_ext)
將是您需要知道的最重要的一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.