如何从作业内部将csv文件写入S3



我为我的应用程序的客户提供了一个数据备份系统。我收集所有相关的csv文件并压缩它们。zip文件完成后,我会将其附在电子邮件中。由于heroku的文件系统,这个过程在heroku上中断。我认为,由于heroku-16,我们可以写入app/tmp目录,这个过程可能发生在同一事务中,文件也会很好,但事实并非如此。在生产中,我似乎甚至没有将文件写入tmp目录(在Dev中(。

所以,我想做的是直接将csv文件写入S3,然后压缩这些文件,并将.Zip保存到S3…然后,将该文件作为电子邮件附件。要做到这一点,我需要生成csv文件,并从ActiveJob内部将它们写入S3。我已经使用S3作为ActiveStorage的一部分,但这个过程不会使用ActiveStorage。

有没有一个命令可以让我手动直接上传到S3存储桶。我一直在查阅文件等,但不知道我在找什么。

作业(使用/tmp(

def perform(company_id, recipient_id)
company         = Company.find(company_id)
source_folder   = "#{ Rails.root }/tmp"
zipfile_name    = "company_#{ company.id }_archive.zip"
zipfile_path    = "#{ Rails.root }/tmp/#{ zipfile_name }"
input_filenames = []
# USERS: create a new empty csv file,
# ... then add rows to it
# ... and, add the file name to the list of files array
users_file_name = "#{ company.name.parameterize.underscore }_users_list.csv"
input_filenames << users_file_name
users_csv_file = File.new("#{ Rails.root.join('tmp') }/#{ users_file_name }", 'w')
users_csv_file << company.users.to_csv
users_csv_file.close
...
# gather up the created files and zip them
Zip::File.open(zipfile_path, create: true) do |zipfile|
input_filenames.uniq.each do |filename|
zipfile.add(filename, File.join(source_folder, filename))
end
end
puts "attaching data_export".colorize(:red)
company.data_exports.attach(
io: StringIO.new("#{ Rails.root }/tmp/company_14_#{ Time.current.to_date.to_s }_archive.zip"),
filename: 'company_14_archive.zip',
content_type: 'application/zip'
)
last_id = company.data_exports.last.id
puts "sending mail using company.id: #{ company.id }, recipient_id: #{ recipient_id }, company.data_exports.last.id: #{ last_id }".colorize(:red)
CompanyMailer.mail_data_export(
company.id,
recipient_id,
last_id
)
end

您可以在S3 上上传这样的文件

key = "file_name.zip"
file_path = "tmp/file_name.zip"
new_s3_client = Aws::S3::Resource.new(region: 'eu-west-1', access_key_id: '123', secret_access_key: '456')
new_bucket = new_s3_client.bucket('public')
obj = new_bucket.object(key)
obj.upload_file(file_path)

最新更新