gpt4 book ai didi

ruby - 如何使用 Ruby 将文件内容从 S3 存储桶下载到内存中

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:37 27 4
gpt4 key购买 nike

我在 Amazon AWS S3 中有一个存储桶,其中有一个名为 users.csv 的文件。

如何使用 Ruby 将此文件的内容从 S3 存储桶加载到内存中以便解析?

这是我的代码:

require 'aws-sdk'
s3 = Aws::S3::Resource.new(region: 'us-west-1')
resp = s3.list_objects(bucket: 'bucket-name', max_keys: 1)
resp.contents.each do |object|
puts #{object.value}
end

当我在 IRB 中尝试这个时,我得到:

struct Aws::S3::Types::Object key="users.csv", last_modified=2017-11-15 19:10:28 UTC, etag="\"9a3d50c07aa4aa6976037ce774294a26\"", size=101, storage_class="STANDARD", owner=struct Aws::S3::Types::Owner display_name="owner-name", id="42093cfa4ccb23a8156cdab8500a41a10bdbf90deebb0ee8a3b340dd1e0c3622"

如何解析 users.csv 的内容?

最佳答案

来自 AWS 文档:

Downloading Objects into Memory

For small objects, it can be useful to get an object and have it available in your Ruby processes. If you do not specify a :target for the download, the entire object is loaded into memory into a StringIO object.

def import_from_s3 

#initiate the client
s3 = Aws::S3::Client.new({
region: region,
access_key_id: key_id,
secret_access_key: secret
})

#Get the object
resp = s3.get_object(bucket: bucket, key: key)

resp.body
#=> #<StringIO ...>

resp.body.read
#=> '...'

Call #read or #string on the StringIO to get the body as a String object.

有关详细信息,请参阅“Downloading Objects from Amazon S3 using the AWS SDK for Ruby”。

关于ruby - 如何使用 Ruby 将文件内容从 S3 存储桶下载到内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47317042/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com