【问题标题】:HTTParty ' get ' returns nil : RubyHTTParty 'get' 返回 nil:Ruby
【发布时间】:2017-01-19 20:13:59
【问题描述】:

我是 Ruby on Rails 框架的新手。我在 coursera 上的 Ruby on Rails 教程中进行了练习,为此我必须使用 HTTParty 从 Coursera API 获取有关某些课程的信息,并在屏幕上显示此信息。但不幸的是,我遇到了一个问题。

这是我从 Coursera API 获取信息并返回的代码

class Coursera
     include HTTParty

     base_uri 'https://api.coursera.org/api/catalog.v1/courses'
     default_params fields: "smallIcon,shortDescription", q: "search"
     format :json

     def self.for term
         response=get("", query: { query: term})["elements"]
         if(response==nil)
             puts "Got Negative response!"
         else
             puts "Got Positive response!"
             return response
         end
     end
 end

有人能指出为什么'get'返回零。我确定我犯了一些错误,但有人可以指出吗?提前致谢

【问题讨论】:

  • 我建议将您的代码减少到基本的 HTTParty.get(...)['elements'] 有效,然后继续前进直到它再次中断。

标签: ruby-on-rails json ruby web-deployment httparty


【解决方案1】:

很奇怪。看起来 coursera 并不总是返回相同的响应。

require 'httparty'

class Coursera
  include HTTParty

  base_uri 'https://api.coursera.org/api/catalog.v1/courses'
  default_params fields: "smallIcon,shortDescription", q: "search"
  format :json

  def self.for term
    response = get("", query: {query: term})
    puts response.request.last_uri.to_s
    elements = response["elements"]
    if elements
      puts "Got Positive response!"
      response
    else
      puts "Got Negative response!"
    end
  end
end

p Coursera.for 'python'

有时会返回:

https://api.coursera.org/api/catalog.v1/courses?fields=smallIcon%2CshortDescription&q=search&query=python
Got Negative response!
nil

有时:

https://api.coursera.org/api/catalog.v1/courses?fields=smallIcon%2CshortDescription&q=search&query=python
Got Positive response!
#<HTTParty::Response:0x2660970 parsed_response={"elements"=>[{"id"=>119, "shortName"=>"scicomp", "name"=>"High Performance Scientific Computing", "shortDescription"=>"Programming-oriented course on effectively using modern computers to solve scientific computing problems arising in the physical/engineering sciences and other fields. Provides an introduction to efficient serial and parallel computing using Fortran 90, OpenMP, MPI, and Python, and software development tools such as version control, Makefiles, and debugging.", "smallIcon"=>"https://d15cw65ipctsrr.cloudfront.net/00/621b9b2597807229ed0fa605f96cdc/HighPerformanceComputingIma.jpg", "links"=>{}}, {"id"=>87, "shortName"=>"compphoto", "name"=>"Computational Photography", "shortDescription"=>"In this course you will learn about the basics of 
....

【讨论】:

  • 我在其他网站上看到过这种情况。我的猜测一直是他们在负载均衡器后面,并且没有将所有机器更新到相同的版本。基本上,他们的主机不一致。
  • 感谢您的回复埃里克。我已经测试了你的代码,它总是在我的系统上给出“得到肯定的响应”。这很好,但问题是当我在 Rails 应用程序中调用此代码时,我总是得到“get”函数返回的“nil”。 (有一个名为 coursera_controller 的控制器,它使用一些参数调用我上面编写的代码中的“for”函数。视图从控制器获取信息并呈现在屏幕上)。
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多