ruby – OAuth和HTTParty

前端之家收集整理的这篇文章主要介绍了ruby – OAuth和HTTParty前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以将OAuth与HTTParty一起使用?我正在尝试进行 this API调用,但是,与文档相矛盾,它需要身份验证.

在你说“使用特定于Twitter的宝石”之前,请听我说 – 我试过了.我尝试了twitter,grackle和无数其他人,但没有人支持这个特定的API调用.所以,我转向了HTTParty.

那么,我如何在HTTParty中使用OAuth?

解决方法

我一直在使用vanilla OAuth gem来实现一些简单的Twitter API调用.我不需要一个重量级的宝石来做任何事情,而且我已经在使用OAuth,所以“自己动手”的方法似乎是合理的.我知道我没有提到过HTTParty,所​​以请不要因此而告诉我.如果您已经在使用OAuth gem,那么对于其他人来说,这对于简单的Twitter OAuth的本质可能是有用的.

如果它有用,这里是相关的代码(抱歉在开始时混合一些常量和其他变量/方法 – 这是从我的真实代码提取这个的最简单和最准确的方法):

  1. #Set up the constants,etc required for Twitter OAuth
  2. OAUTH_SITE = "https://api.twitter.com"
  3. TOKEN_REQUEST_METHOD = :post
  4. AUTHORIZATION_SCHEME = :header
  5.  
  6. def app_request_token_path
  7. "/oauth/request_token"
  8. end
  9. def app_authorize_path
  10. "/oauth/authorize"
  11. end
  12. def app_access_token_path
  13. "/oauth/access_token"
  14. end
  15. def consumer_key
  16. "your twitter API key"
  17. end
  18. def consumer_secret
  19. "your twitter API secret"
  20. end
  21.  
  22. # Define the OAuth consumer
  23. def consumer meth=:post
  24. @consumer ||= OAuth::Consumer.new(consumer_key,consumer_secret,{
  25. :site => "#{OAUTH_SITE}",:request_token_path=>app_request_token_path,:authorize_path=>app_authorize_path,:access_token_path=>app_access_token_path,:http_method=>:post,:scheme=> :header,:body_hash => ''
  26. })
  27. end
  28.  
  29. # Essential parts of a generic OAuth request method
  30. def make_request url,method=:get,headers={},content=''
  31. if method==:get
  32. res = @access_token.get(url,headers)
  33. elsif method==:post
  34. res = @access_token.post(url,content,headers)
  35. end
  36.  
  37. if res.code.to_s=='200'
  38. jres = ActiveSupport::JSON.decode(res.body)
  39. if jres.nil?
  40. @last_status_text = @prev_error = "Unexpected error making an OAuth API call - response body is #{res.body}"
  41. end
  42. return jres
  43. else
  44. @last_status_text = @prev_error = res if res.code.to_s!='200'
  45. return nil
  46. end
  47. end
  48.  
  49. # Demonstrate the daily trends API call
  50. # Note the use of memcache to ensure we don't break the rate-limiter
  51. def daily_trends
  52.  
  53. url = "http://api.twitter.com/1/trends/daily.json"
  54. @last_status_code = -1
  55. @last_status_success = false
  56. res = Rails.cache.fetch(url,:expires_in=> 5.minutes) do
  57. res = make_request(url,:get)
  58. unless res
  59. @last_status_code = @prev_error.code.to_i
  60. end
  61. res
  62. end
  63. if res
  64. @last_status_code = 200
  65. @last_status_success = true
  66. @last_status_text = ""
  67. end
  68. return res
  69. end

我希望这主要是在更广泛地使用OAuth gem的背景下,可能对其他人有用.

猜你在找的Ruby相关文章