[英]faraday timeout on a simple get
Is there a way to add timeout options in this simple get method?有没有办法在这个简单的 get 方法中添加超时选项?
I am using Faraday 3.3.我正在使用法拉第 3.3。
Faraday.get(url)
After searching around, I can only apply timeout options after I initiate a connection first, then apply timeout options.四处搜索后,我只能在先启动连接后应用超时选项,然后应用超时选项。 Or there's a simple way?
或者有什么简单的方法?
This is what I am doing right now:这就是我现在正在做的事情:
conn = Faraday.new
response = conn.get do |req|
req.url url
req.options.timeout = 2 # 2 seconds
end
Try this one:试试这个:
conn = Faraday.new do |conn|
conn.options.timeout = 20
end
response = conn.get(url)
UPD: After I had reviewed gem sources, I found out that there's no way do it like you want. UPD:在我查看了 gem 来源之后,我发现没有办法像你想要的那样做。
With get
method you can set only url, request params and headers .使用
get
方法,您只能设置url、request params 和 headers 。 But to specify timeout, you have to access @options
of Faraday::Connection
instance.但是要指定超时,您必须访问
Faraday::Connection
实例的@options
。 And you can do this by using attr_reader :options
你可以通过使用
attr_reader :options
来做到这一点
conn = Faraday::Connection.new
conn.options.timeout = 20
Or on initialization of Faraday::Connection instance:或者在 Faraday::Connection 实例的初始化上:
Faraday::Connection.new(nil, request: { timeout: 20 })
Or when it copies connection parameters to request parameter and yields request back :或者当它将连接参数复制到请求参数并返回请求时:
Faraday::Connection.new.get(url) { |request| request.options.timeout = 20 }
I had the same problem and I ended up doing something like this so I can more easily stub the code in testing:我遇到了同样的问题,最后我做了这样的事情,这样我就可以更轻松地在测试中存根代码:
def self.get(url, params: {}, headers: {}, timeout: 2)
conn = Faraday.new(
params: params,
headers: headers
) do |conn|
conn.options.timeout = timeout
end
conn.get(url)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.