加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – OAuth和HTTParty

发布时间:2020-12-17 04:16:11 所属栏目:百科 来源:网络整理
导读:是否可以将OAuth与HTTParty一起使用?我正在尝试进行 this API调用,但是,与文档相矛盾,它需要身份验证. 在你说“使用特定于Twitter的宝石”之前,请听我说 – 我试过了.我尝试了twitter,grackle和无数其他人,但没有人支持这个特定的API调用.所以,我转向了HTTP
是否可以将OAuth与HTTParty一起使用?我正在尝试进行 this API调用,但是,与文档相矛盾,它需要身份验证.

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

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

解决方法

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

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

#Set up the constants,etc required for Twitter OAuth
OAUTH_SITE = "https://api.twitter.com"
TOKEN_REQUEST_METHOD = :post
AUTHORIZATION_SCHEME = :header 

  def app_request_token_path 
    "/oauth/request_token"  
  end    
  def app_authorize_path 
    "/oauth/authorize"  
  end      
  def app_access_token_path        
    "/oauth/access_token"        
  end
  def consumer_key
    "your twitter API key"
  end
  def consumer_secret
    "your twitter API secret"
  end

  # Define the OAuth consumer
  def consumer meth=:post
    @consumer ||= OAuth::Consumer.new(consumer_key,consumer_secret,{
      :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 => ''
    })
  end            

  # Essential parts of a generic OAuth request method
  def make_request url,method=:get,headers={},content=''                  
    if method==:get
      res = @access_token.get(url,headers)
    elsif method==:post
      res = @access_token.post(url,content,headers)
    end

    if res.code.to_s=='200'
      jres = ActiveSupport::JSON.decode(res.body)
      if jres.nil?
        @last_status_text = @prev_error = "Unexpected error making an OAuth API call - response body is #{res.body}"
      end      
      return jres
    else
      @last_status_text = @prev_error = res if res.code.to_s!='200'
      return nil      
    end
  end

# Demonstrate the daily trends API call
# Note the use of memcache to ensure we don't break the rate-limiter
  def daily_trends

     url = "http://api.twitter.com/1/trends/daily.json"     
     @last_status_code = -1
     @last_status_success = false
     res = Rails.cache.fetch(url,:expires_in=> 5.minutes) do
       res = make_request(url,:get)          
       unless res
         @last_status_code = @prev_error.code.to_i
       end
       res
     end                 
     if res
         @last_status_code = 200
         @last_status_success = true
         @last_status_text = ""
     end
     return res
  end

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读