2013-03-03 28 views
0

我正在閱讀有關Rack :: Throttle,我想將默認客戶端標識符從IP更改爲其他某些。該文件說可以完成子類Rack :: Throttle

由Rack :: Throttle存儲和維護的限速計數器是 鍵入唯一的HTTP客戶端。

默認情況下,HTTP客戶端由Rack :: Request#ip返回的IP地址 唯一標識。如果您希望改爲使用更詳細的特定於應用程序的標識符(例如會話密鑰或 用戶帳戶名稱),則只需實施限制策略的子類 實施並覆蓋#client_identifier方法。

我不知道在哪裏添加,在這裏是我目前的另一種方法的子類。有人知道怎麼做這個嗎? https://github.com/datagraph/rack-throttle

module Rack 
    module Throttle 
    class DailyRequests < Daily 
     def allowed?(request) 
     ## Insert rules 
     super request 
     end 
    end 

    class HourlyRequests < Hourly 
     def allowed?(request) 
     ## Insert rules 
     super request 
     end 
    end 

    class RequestInterval < Interval 
     def allowed?(request) 
     ## Insert rules 
     super request 
     end 
    end 
    end 
end 
+0

[覆蓋client_identifier方法](https://github.com/datagraph/rack-throttle/blob/master/lib/rack/throttle/limiter.rb#L157),我想。 – Zabba 2013-03-03 05:49:29

回答

1

你應該繼承現有rack-throttle類(大概無論是Rack::Throttle::IntervalRack::Throttle::TimeWindow,哪一個與您的需求更加貼緊)之一,覆蓋#client_identifier方法。

#client_identifier傳遞一個參數,request,這是在傳入的HTTP請求,通過了Rack::Request實例包含的信息,可用於獲取信息,如HTTP頭,Cookie路徑,並根據您的應用程序可能還有其他信息。默認實現查找like this

# @param [Rack::Request] request 
# @return [String] 
def client_identifier(request) 
    request.ip.to_s 
end 

這裏的子類Rack::Throttle::Interval的一個例子,以匹配查詢參數的要求,如?user_id=<id>

class UserThrottle < Rack::Throttle::Interval 
    def client_identifier(request) 
    request['user_id'] 
    end 
end 

,你可能use與機架應用:

use UserThrottle, :min => 100 

請注意,您仍然可以將諸如:min之類的選項傳遞到機架use聲明,因爲它只是對現有節氣門類進行子類化。在Rails應用中採用這種方法只需要在application.rb文件中調用use(請參閱Rails on Rack)。

+0

謝謝你這個工作 – 2013-03-08 19:29:26