Module: Monkeylearn::Requests

Included in:
Categories, Classifiers, Extractors, Pipelines
Defined in:
lib/monkeylearn/requests.rb

Instance Method Summary collapse

Instance Method Details

#get_connectionObject



35
36
37
38
39
# File 'lib/monkeylearn/requests.rb', line 35

def get_connection
  @conn ||= Faraday.new(url: Monkeylearn.api_endpoint) do |faraday|
    faraday.adapter Faraday.default_adapter # Net::HTTP
  end
end

#request(method, path, data = nil, query_params = nil) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/monkeylearn/requests.rb', line 7

def request(method, path, data = nil, query_params = nil)
  response = get_connection.send(method) do |req|
    url = path.to_s
    if query_params
      url += '?' + URI.encode_www_form(query_params)
    end
    req.url url
    req.headers['Authorization'] = 'Token ' + Monkeylearn.token
    req.headers['Content-Type'] = 'application/json'
    if data
      req.body = data.to_json
    end
  end
  if Monkeylearn.wait_on_throttle && seconds = throttled?(response)
    # Request was throttled, wait 'seconds' seconds and retry
    sleep seconds
    response = request(method, path, data)
  end
  Monkeylearn::Response.new(response)
end

#throttled?(response) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
# File 'lib/monkeylearn/requests.rb', line 28

def throttled?(response)
  return false if response.status != 429
  error_detail = JSON.parse(response.body)['detail']
  match = /available in ([\d]+) seconds/.match(error_detail)
   if match then match[1].to_i else false end
end