cron crawler使用Ruby中的Google API将数据插入Google电子表格的授权问题

时间:2015-05-25 07:40:07

标签: ruby cron google-api web-crawler google-api-client

我的项目是抓取特定的网络数据,并在每天早上9点将它们放入我的Google电子表格中。它必须获得阅读和授权的授权。写一些东西。这就是为什么下面的代码位于顶部。

# Google API
CLIENT_ID = blah blah
CLIENT_SECRET = blah blah
OAUTH_SCOPE = blah blah
REDIRECT_URI = blah blah

# Authorization_code
def get_authorization_code 
    client = Google::APIClient.new
    client.authorization.client_id = CLIENT_ID
    client.authorization.client_secret = CLIENT_SECRET
    client.authorization.scope = OAUTH_SCOPE
    client.authorization.redirect_uri = REDIRECT_URI

    uri = client.authorization.authorization_uri
    Launchy.open(uri)

    # Exchange authorization code for access token
    $stdout.write  "Enter authorization code: "
    client.authorization.code = gets.chomp
    client.authorization.fetch_access_token!
    client.authorization
end

authorization_code = get_authorization_code
access_token  = authorization_code.access_token
session = GoogleDrive.login_with_oauth(access_token)

但是在代码中,即使我设置了cron作业,我可能必须在早上醒来并Enter authorization code才能完成它。但我不想。

请告诉我如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

感谢Ruby google_drive gem oAuth2 saving

我需要获取刷新令牌并让我的代码像下面一样使用它。

CLIENT_ID = '!!!'
CLIENT_SECRET = '!!!'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
REFRESH_TOKEN = '!!!'

client = Google::APIClient.new
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.scope = OAUTH_SCOPE
client.authorization.redirect_uri = REDIRECT_URI
client.authorization.refresh_token = REFRESH_TOKEN
client.authorization.refresh! 

access_token = client.authorization.access_token
session = GoogleDrive.login_with_oauth(access_token)