2016-02-29 92 views
0

我正在使用sitemap_generator創建站點地圖。 我有一個rake任務來創建s站點地圖並將其上傳到s3。Rails,sitemap_generator,s3,如何將公共可用的文件寫入s3?

sitemap.rb

SitemapGenerator::Sitemap.default_host = "https://www.ezpoisk.com" 
SitemapGenerator::Sitemap.create_index = true 
SitemapGenerator::Sitemap.public_path = 'tmp/' 
SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/' 

SitemapGenerator::Sitemap.create do 
# generating links ... 

rake任務

require "aws" 

namespace :sitemap do 
    desc "Upload the sitemap files to S3" 
    task upload_to_s3: :environment do 
    puts "Starting sitemap upload to S3..." 

    s3 = AWS::S3.new(access_key_id: ENV["AWS_ACCESS_KEY_ID"], 
        secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]) 

    bucket = s3.buckets[ENV["S3_BUCKET_NAME"]] 

    Dir.entries(File.join(Rails.root, "tmp", "sitemaps")).each do |file_name| 
     next if ['.', '..', '.DS_Store'].include? file_name 
     path = "sitemaps/#{file_name}" 
     file = File.join(Rails.root, "tmp", "sitemaps", file_name) 

     begin 
     object = bucket.objects[path] 
     object.write(file: file) 
     rescue Exception => e 
     raise e 
     end 
     puts "Saved #{file_name} to S3" 
    end 
    end 

    desc 'Create the sitemap, then upload it to S3 and ping the search engines' 
    task create_upload_and_ping: :environment do 
    Rake::Task["sitemap:create"].invoke 

    Rake::Task["sitemap:upload_to_s3"].invoke 

    url = "https://www.ezpoisk.com/sitemaps/sitemap.xml.gz" 
    SitemapGenerator::Sitemap.ping_search_engines(url) 
    end 
end 

,我希望能夠以服務如果從S3通過我的網站,以便在路線

get "sitemaps/sitemap(:id).:format.:compression" => "sitemap#show" 

和sitemaps_controller

def show 
    data = open("https://s3.amazonaws.com/#{ENV['S3_BUCKET_NAME']}/sitemaps/sitemap#{params[:id]}.xml.gz") 
    send_data data.read, :type => data.content_type 
    end 

現在。問題。

當我運行rake任務並嘗試通過鏈接訪問文件時,我得到403禁止。然後,我去s3控制檯,並手動在「sitemaps」文件夾中「公開」。現在,當我嘗試訪問文件時,它已正確下載... 問題是 - 當我再次運行任務時(我有一個sidekiq工作,每天都會執行一次),我再次得到403 ...我的假設是我寫的操作會更改此權限。

該存儲桶本身具有「允許所有人列表」的權限。

我試圖

bucket = s3.buckets[ENV["S3_BUCKET_NAME"]] 
bucket.acl = :public_read 
在rake任務

,但它似乎並沒有生效。 我錯過了一些東西,必須有兩種方法來設置一個標誌寫入,以使其公開,或者,我不會正確初始化它。

回答