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

2024-05-11

我的项目是每天早上 9:00 抓取某些网络数据并将它们放入我的 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完成它。但我不想。

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


解决了感谢Ruby google_drive gem oAuth2 保存 https://stackoverflow.com/questions/26789804/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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

cron 爬虫使用 Ruby 中的 Google API 将数据插入 Google 电子表格的授权问题 的相关文章

随机推荐