我在我的rails 3应用程序中使用rack-throttle
作为速率限制引擎。我已经基于Rack::Throttle::Interval
创建了自己的类来定义自定义速率限制逻辑。我正在检查请求是否是针对确切的控制器和确切的操作。如果我发出GET
请求,这样可以正常工作。但是,如果我发送POST
请求,我会遇到一些问题。
class CustomLimiter < Rack::Throttle::Interval
def allowed?(request)
path_info = Rails.application.routes.recognize_path request.url rescue path_info = {}
if path_info[:controller] == "some_controller" and path_info[:action] == "some_action"
super
else
true
end
end
end
以下是我的控制器操作
def question
#user is redirected here
end
def check_answer
#some logic to check answer
redirect_to question_path
end
我的路线
get "questions" => "application#question", :as => "question"
post "check_answer" => "application#check_answer", :as => "check_answer"
编辑:
问题是POST
请求即将到来,以便调用方法allowed?
。但是,当我致电Rails.application.routes.recognize_path
时,我得到Route set not finalized
例外。如何在rack-throttle
中间件已添加到application.rb
class Application < Rails::Application
#Set up rate limiting
config.require "ip_limiter"
config.require "ip_user_agent_limiter"
config.middleware.use IpLimiter, :min => 0.2
config.middleware.use IpUserAgentLimiter, :min => 2
end
IpLimiter
和IpUserAgentLimiter
都来自自定义限制器
答案 0 :(得分:2)
在阅读了Rails.application.routes.recognize_path(http://apidock.com/rails/ActionDispatch/Routing/RouteSet/recognize_path)的代码之后,这个方法获得了第二个args,您可以在其中传递METHOD。
尝试:
path_info = Rails.application.routes.recognize_path(request.url, {:method => request.request_method}) rescue path_info = {}
我认为所有方法都可行。
答案 1 :(得分:0)
这个对我有用,可以捕获所有POST请求,并忽略所有GET请求:
class CustomLimiter < Rack::Throttle::Interval
def allowed?(request)
return true unless request.request_method == "POST"
super request
end
end