ruby rest-client: make it never timeout?

两盒软妹~` 提交于 2019-12-03 10:57:40
phlipper

This syntax sets the timeout as request header (see RestClient.post signature), if you want to use the timeout parameter you must use:

RestClient::Request.execute(:method => :post, :url => @url, :timeout => 90000000)

see: https://github.com/rest-client/rest-client/blob/master/lib/restclient/request.rb#L12

Looking at the docs, you can pass -1 through RestClient.execute timeout param:

# * :timeout and :open_timeout passing in -1 will disable the timeout by setting the corresponding net timeout values to nil

It can be used as follows:

resource = RestClient::Resource.new(
  "url",
  :timeout => -1,
  :open_timeout => -1
response = resource.get :params => {<params>}

I have used following code and works like a charm as pointed out by Richard

resource = RestClient::Resource.new "url", 
                                    :timeout => $TIMEOUT, 
                                    :open_timeout => $OPEN_TIMEOUT

response = resource.get  :params => { ..... }

I already use RestClient.get and RestClient.post extensively, so for me, it was easier to 'Monkey Patch' RestClient. I would recommend using RestClient::Resource.new or RestClient::Request.Execute if possible.

However, since I'm lazy, and don't want to go swap out every occurrence of RestClient.get / RestClient.post in my code, I've decided to take a shortcut.

$timeout = 30
$open_timeout = 30

module RestClient2
  include RestClient

  def self.get(url, headers={}, &block)
    Request.execute(:method => :get, :url => url, :headers => headers, 
     :timeout => $timeout, :open_timeout => $open_timeout, &block)
  end

  def self.post(url, payload, headers={}, &block)
    Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers,
     :timeout => $timeout, :open_timeout => $open_timeout, &block)
  end
end

And than I just just quick replaced RestClient.get/post with RestClient2.get/post.

It would be nice, if RestClient::Request had a default timeout specified, like:

  @timeout = args[:timeout] || 30
  @open_timeout = args[:open_timeout] || 30

I'm having similar issues. A quick dive into the source reveals this bit of unfriendliness:

def self.post(url, payload, headers={}, &block)
  Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers, &block)
end

Unless I'm missing something, the timeout options aren't passed on to the underlying request. Time for a patch ...

The RestClient::Resource.new() allows you to set :timeout and :open_timeout values that will get passed to the Request.execute method, when you use the resource's get, post, put, etc methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!