AWS :: S3 ::错误:: NoSuchKey:没有此类错误

时间:2015-06-01 17:18:06

标签: ruby-on-rails ruby amazon-web-services amazon-s3

我尝试创建一个删除S3实例上文件的方法,但是当我尝试调用AWS::S3::Errors::NoSuchKey: No Such Key或。.head时,我收到read错误一个对象。

应用程序/模型/ file_item.rb

def thumbnail
    {
      exists: thumbnailable?,
      small: "http://#{bucket}.s3.amazonaws.com/images/#{id}/small_thumb.png",
      large: "http://#{bucket}.s3.amazonaws.com/images/#{id}/large_thumb.png"
    }
end 

LIB /适配器/ amazons3 / accessor.rb

module Adapters
  module AmazonS3
    class Accessor
      S3_BUCKET =  AWS::S3.new.buckets[ENV['AMAZON_BUCKET']]

      ...

      def self.delete_file(thumbnail)
        prefix_pattern = %r{http://[MY-S3-HOST]-[a-z]+.s3.amazonaws.com/}
        small_path = thumbnail[:small].sub(prefix_pattern, '')
        large_path = thumbnail[:large].sub(prefix_pattern, '')
        small = S3_BUCKET.objects[small_path]
        large = S3_BUCKET.objects[large_path]
        binding.pry
        S3_BUCKET.objects.delete([small, large])
      end
    end
  end
end

示例url1

"http://projectname-staging.s3.amazonaws.com/images/994/small_thumb.png"

示例url2

"http://projectname-production.s3.amazonaws.com/images/994/large_thumb.png"

2 个答案:

答案 0 :(得分:1)

为ruby假设awssdk v1。

small = S3_BUCKET.objects[small_path]

实际上并没有获得任何对象。

来自:https://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/Bucket.html

bucket.objects['key'] #=> makes no request, returns an S3Object

bucket.objects.each do |obj|
  puts obj.key
end

因此您需要将代码更改为:

to_delete = []
S3_BUCKET.objects[small_path].each do |obj|
  to_delete << obj.key
end
S3_BUCKET.objects[large_path].each do |obj|
  to_delete << obj.key
end

S3_BUCKET.objects.delete(to_delete)

刚刚搞砸了代码,所以想法就在那里,你可能需要纠正/抛光一下

答案 1 :(得分:1)

由于您对@Mircea的回答,我能够得到一种不同的解决方案。

def self.delete_file(thumbnail)
  folder = thumbnail[:small].match(/(\d+)(?!.*\d)/)
  to_delete = []
  S3_BUCKET.objects.with_prefix("images/#{folder}").each do |thumb|
    to_delete << thumb.key
  end
  # binding.pry
  S3_BUCKET.objects.delete(to_delete)
end