404 error with open-uri in a rake task… what's causing it?

纵然是瞬间 提交于 2019-12-04 00:17:21

The embed.ly api returns a 404 if the specified resource(video/picture) doesn't exist. OpenURI handles this as an exception. To catch the error you could do something like this:

task :embedly => :environment do
  require 'json'
  require 'uri'
  require 'open-uri'

  Video.all.each do |video|
    begin
      json_stream = open("http://api.embed.ly/1/oembed?key=08b652e6b3ea11e0ae3f4040d3dc5c07&url=#{video.video_url}&maxwidth=525")
      ruby_hash = JSON.parse(json_stream.read)
      thumbnail_url = ruby_hash['thumbnail_url']
      embed_code = ruby_hash['html']
      video.update_attributes(:thumbnail_url => thumbnail_url, :embed_code => embed_code)
    rescue OpenURI::HTTPError => ex
      puts "Handle missing video here"
    end 
  end  
end

You could also check if the videos/urls are valid before running the task.

You're not URL encoding your video.url:

json_stream = open("...url=#{video.video_url}...")

so you're probably producing a mangled URL and api.embed.ly is telling you that it can't find it. For example, if video.video_url is http://a.b?c=d&e=f, then e=f will be seen as a parameter for http://api.embed.ly/1/oembed rather than getting passed on through to http://a.b.

You might want to do this instead:

require 'cgi'
#...
json_stream = open("...url=#{CGI.escape(video.video_url)}...")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!