brcebn
brcebn

Reputation: 1722

Net::ReadTimeout with local URI

I'm trying to understand why is the following method is blocking my app.

url = 'http://192.168.1.33/assets/my_small_pic.jpg'
image_file = open(url).read

It's working perfectly when I try it in the console. But when I do it from an API method, it blocks my app and after a long while I have the following error:

Net::ReadTimeout (Net::ReadTimeout)

What does my app not like my way of reading the file?

Upvotes: 2

Views: 890

Answers (1)

Eugene Myasyshchev
Eugene Myasyshchev

Reputation: 4635

I assume you're using 'open-uri' and the api is a part of the same RoR app where you're sending the request to. In this case your app is just being blocked by the first request while you send a second request to it so the second request gives a timeout. You should see this issue in development only. In production things will be a bit different since static assets to be served by the Nginx or Apache. Additionally Rails 4 is by default is thread safe in production which means it can serve multiple requests at a time. So if you're on Rails4 then in production calls to other apis will work as well. For Rails3 you would have to explicitly specify config.threadsafe!

In general I would recommend you to access resources or make any other API calls from the same app directly. It's more efficient. In your example above you can read the file like this:

File.read(File.join(Rails.root, 'public/assets/my_small_pic.jpg'))

If you still want to send the request then to make it work in development you have to start a new thread similar to this:

Thread.new do
  open('http://192.168.1.33/assets/my_small_pic.jpg').read
end

Upvotes: 1

Related Questions