Ruby - 用于速率限制的访问响应标头(帮助侦察程序)

时间:2018-02-11 22:45:32

标签: ruby rate-limiting

我正在使用helpscout ruby​​ gem并尝试检查请求限制何时低于某个数字(即剩余2个请求)并在剩余时间间隔内休眠以允许速率限制为复位。

在发出请求时,有没有办法从API访问响应头? https://developer.helpscout.com/help-desk-api/#basic-rate-limiting

X-RateLimit-Interval-*  Length of the rate limiting interval in seconds

X-RateLimit-Limit-* Maximum number of requests per interval

X-RateLimit-Remaining-* Number of requests remaining in the current rate limit interval

对讲机(https://developers.intercom.com/reference#rate-limiting)允许您检查rate_limit_details并返回标题,但我找不到任何帮助Scout的内容或了解如何访问它们。

intercom.rate_limit_details
#=> {:limit=>180, :remaining=>179, :reset_at=>2014-10-07 14:58:00 +0100}

1 个答案:

答案 0 :(得分:5)

问题是helpscout gem没有捕获该信息。如果你看一下源代码

https://github.com/hramos/helpscout/blob/db8da936853c8df694186ab11100d4482f74d302/lib/helpscout/models.rb#L44

  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
    end
  end

发生错误时,他们只捕获statusmessage。如果要捕获其他标题值

,可以增强下面的类
  # Error Envelope
  class ErrorEnvelope
    attr_reader :status, :message, :limit

    # Creates a new ErrorEnvelope object from a Hash of attributes
    def initialize(object)
      @status = object["status"]
      @message = object["message"]
      @limit = object["header"]["X-RateLimit-...."]
    end
  end

但是这只会在你收到错误时告诉你限制。您可以进一步增强库以在每次调用时捕获这些限制。您需要修改client.rb

https://github.com/hramos/helpscout/blob/2449bc2604667edfca5ed934c8e61cd129b17af5/lib/helpscout/client.rb

module HelpScout
  class Client
    include HTTParty
    @@last_headers

    def self.get(*more)
        response = HTTParty.get(*more)
        @@last_headers = response.headers
        return response
    end

    def self.last_headers
        @@last_headers
    end

    ....
    ....
 end

这样做HelpScout.last_headers将为您提供上次回复的标题,然后您可以从相同的

中捕获所需的任何字段